﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
using Telerik.WinControls.UI;
using Telerik.WinControls;
using Telerik.Reporting;
using System.Diagnostics;
using System.Configuration;
using APC.Common; //Database Handling - UI Language - Icon Gallery
using APC.Properties;
using System.Globalization;

namespace APC
{
    public partial class frmMain : Form
    {

        #region Enum

        private enum TagType { TypeCommand, TypeWeightKg, TypeWeightTon, TypeWeightProcent }
  
        private enum BatchStatusType { pending, weighing, mixing, scale3, hammermill, cooling, storage }

        private enum OrderStatusType { TypeOK, TypeAlert, TypeError, TypeLock }
        private enum OrderStatusScope
        {
            TypeOrderStorageMissing,
            TypeOrderProcentDeviation,
            TypeOrderRunning,
            TypeOrderContamination,
            TypeLocationMissing,
            TypeMinBatchSize,
            TypeOrderReady,
            TypeOrderLocked
        }
    
        private enum MenuAction // Number is = Id from table: MenuSystem
        {
            ReportViewer = 4,
            OrderHandlingNewOrder = 8,
            RawMaterialAddNew = 14,
            RawMaterialList = 16,
            RawMaterialLocation = 21, //TODO: Must be dynamic = Locations will be loaded in treeview from database
            RecipeAddNew = 33,
            OrderOrderList = 35, // Pending and running orders
            LocationLocationGroups = 46,
            RecipeList = 47
        }

        private enum SaveAction { TypeNew, TypeEdit, TypeDelete }

        private enum ObjectType { TypeOrder, TypeRecipe, TypeRawMaterial, TypeLocation, TypeReport }

        #endregion

        #region Declarations

        private bool IsDirty = false; //If a record is changed this will raise an alert: "Will you save changes?"

        private SaveAction _SaveAction; //New or Edit
        private int _ObjectID; //ID of modified object: e.g. Raw Material, a Location or a Recipe etc
        private int _LocationId;
        private int _RawMaterialId;
        private int _OrderId = 0;
        private int _RecipeId = 0;
        private int _OrderSequence = 0;
        private string _OrderPostfixNumber = "";

        private int ValidationMessagesCount = 0;

        private int BatchCounter = 1;
        private MenuAction SelectedMenu;
        private RadPageViewPage pv;
        private RadTreeView tree;
 
        private IconLibrary ImageList;

        //Flags
        private bool RawMaterialChanged = false;
        private bool RawMaterialIsLoaded = false;

        //private bool Dragable = false;
        //private bool ReloadGrid = true; //Flag to dertermine if grid must be reloaded if user changes values of e.g a orders quantum etc
        //private bool FirstRun = true;
        
        private String UIlang = "en-US"; //Default language
        //private List<APC.Common.TagListe> TagList;
        //private List<APC.Common.TagListe> TagListFull; //Holds full TagName list
        private List<MenuSystem> Menu;
        private MenuObject MenuClass;
        private RadTreeNode DragNode;

        private List<RawMaterials> ListIngridients;
        private List<RawMaterials> ListNegativeRawMaterials;
        private ListViewDataItem SelectedListItem;

        Recipe rcp;
        InputValidator validator;
        //bool TextBoxIsValidated = false;

        #endregion

        #region MessageBox Const
        //MessageBox constants: 
        //Title of messagebox starts with "Title..." 
        //Message of MessageBox starts with "Message..."
        
        const string TitleOrderValidation = "Order Validation";
        const string MessageOrderValidation = "There is found one or more non-conformity - please see status list for info!";
        const string MessageValidationLocationMissing = "Ingridient Location missing - click on 'Select Location'!";
        const string MessageValidationOrderContamination = "Contamination risk from previous order: {0}";
        const string MessageValidationOrderProcentDeviation = "Amount procent is different from 100%!";
        const string MessageValidationOrderIsRunning = "Order {0} is running and can not be edited!";
        const string MessageValidationStorageLocationMissing = "'Storage Location' missing!";
        const string MessageValidationMinBatchSize = "Minimum batch size conflict!";
        const string MessageValidationOrderIsReady = "Order {0} is ready for Production!";
        const string MessageValidationOrderLocked = "Order {0} is locked while edited!";

        const string MessageLocationAlraedyInList = "This location is already in list!";
        const string TitleLocation = "Location";

        const string MessageIngridientAlreadyInList = "This ingridient is already in list!";

        const string MessageRawImaterialNameOrNumberMissing = "Please give raw material a name and a number!";
        const string TitleRawImaterialNameOrNumberMissing = "Raw Material";

        const string MessageIngridientMissing = "Please assign 1 ore more Ingredients!";

        const string MessageSendToProduction = "Send Order to Production?";
        const string MessageOrderIsLocked = "This order can not be removed as it is already in Production!";
        const string MessageRemoveOrder = "Remove this order: {0}?";
        const string TitleOrder = "Order";

        const string MessageRawMaterialDelete = "Delete this raw material?";
        const string TitleRawMaterial = "Raw Material";

        const string TitleRecipe = "Recipe";
        const string MessageRecipeDelete = "Delete selected Recipe?";
        const string MessageRecipeNameMissing = "Please give Recipe a name!";
        const string MessageRecipeNumberMissing = "Please give Recipe a number!";
        const string MessageRecipeEndProductNameMissing = "Please give Recipe a end product name!";
        const string MessageRecipeDefaultQuantityMissing = "Please give Recipe a default order quantity!";
        const string MessageRecipeRecBatchSizeMissing = "Please give Recipe a recommend batch size!";
        const string MessageRecipeMinBatchSizeMissing = "Please give Recipe a minimum batch size!";
        const string MessageRecipeTotalAmountNot100Procent = "Total of amount procent is below or above 100%!";
        const string MessageRecipeIngridientAmountProcentMissing = "Please give each ingridient a amount procent!";
        const string MessageRecipeNameOrNumberMissing = "Please give recipe a name and a number!";

        const string MessageIngridientRemove = "Remove selected Ingridient?";
        const string TitleIngridient = "Ingridient";


        #endregion

        #region Constructor

        public frmMain()
        {
            InitializeComponent();
            LoadSystem();

            //this.lstOrderRecipeIngridients.CellCreating += new Telerik.WinControls.UI.ListViewCellElementCreatingEventHandler(lstRecipe_CellCreating);

            //this.lstRecipeIngredients.ListViewElement.DragDropService.PreviewDragDrop += new EventHandler<Telerik.WinControls.RadDropEventArgs>(DragDropService_PreviewDragDrop);
        }

        #endregion

        #region Methods

        /// <summary>
        /// Sends the calculated batch collection to database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendToBatchListe()
        {
            Batch batch;
            List<TagValuePair> TagValuePairs;
            Tag tg = new Tag();

            foreach (ListViewDataItem lst in this.lstBatch.Items)
            {
                if (lst.Tag != null)
                {
                    batch = (Batch)lst.Tag;

                    if (batch.TagValuePairs != null)
                    {
                        TagValuePairs = batch.TagValuePairs;

                        foreach (TagValuePair tvp in TagValuePairs)
                        {
                            APC.Common.BatchListe bl = new APC.Common.BatchListe();
                            bl.OrderId = this._OrderId;
                            bl.BatchNo = batch.BatchNumber;
                            bl.ZenonControlId = batch.ZenonControlId;
                            bl.TagListeId = tvp.TagListeId;
                            bl.TagListGroupId = tvp.TagListeGroupId; //TagListeGroupId is Id e.g. for "Scale 1" or "Scale 2"

                            if (tvp.TagListeId == tg.FindTagIdOnTagName("APC_PLC_SCALE_ORDER_ID")) // Find TagListe.Id for string "APC_PLC_SCALE_ORDER_ID" in TagListe
                            {
                                bl.Value = this._OrderId.ToString();
                            }
                            else
                            {
                                bl.Value = tvp.TagValue;
                            }

                            bl.SendToZenon = batch.SendToZenon;
                            bl.Status = batch.Status; //Default is 0. User can modify if still 0
                            bl.BatchCountNo = batch.BacthCountNumber;
                            bl.CreateDateTime = DateTime.Now;
                            bl.UpdateDateTime = DateTime.Now;
                            bl.OrderSequence = this._OrderSequence;

                            batch.SaveItem(bl);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Shows running orders/batches with status
        /// </summary>
        private void LoadLiveBatchData()
        {

            this.lstBatch.Items.Clear();
            ListViewDataItem lst;
            Batch b = new Batch();
            string status;

            lstBatch.Columns.RemoveAt(3);
            lstBatch.Columns.Add("Column34", "Status");
            lstBatch.Columns[3].Width = 74;

            string img;

            foreach (LiveBatch i in b.ListRunningOrderBatchList().OrderByDescending(x => x.OrderSequence))
            {
                img = i.Status > 0 ? "batch" : "process"; //Show blue => or green => icon as process indicator

                status = ((BatchStatusType) i.Status).ToString();

                lst = new ListViewDataItem();
                lst.Tag = null;
                lst.Image = SetIcon(img);
                lst.SubItems.Add("");
                lst.SubItems.Add(i.BatchCountNumber.ToString());
                lst.SubItems.Add(i.RecipeName);
                lst.SubItems.Add(status);

                lstBatch.Items.Add(lst);
            }

            Order o = new Order();
            //Get orders where one ore more batches are in PLC/Zenon
            List<Order> OrderList = o.GetOrdersInProcess();

            grpActiveOrders.Controls.Clear();

            //Set height of group box depending on number of active orders
            grpActiveOrders.Height = 20 + (35 * OrderList.Count);
  
            RadProgressBar pgb;
            int h = 25;
            foreach (Order order in OrderList)
            {
                //Add progressbar runtime and load with order status data
                pgb = new RadProgressBar();
                pgb.Tag = order.Id;
                pgb.Text = order.StartDate.ToShortDateString() + " " + order.StartDate.ToShortTimeString() + " " + order.RecipeName.Trim();
                pgb.TextAlignment = System.Drawing.ContentAlignment.MiddleLeft;
                pgb.Maximum = order.OrderBatchTotal;
                pgb.Value1 = order.OrderCalcultatedStatus;
                pgb.Width = 225;
                pgb.Height = 20;
                pgb.Left = 10;
                pgb.Top = h;

                pgb.Click += new EventHandler(RadProgressBar_Click);

                grpActiveOrders.Controls.Add(pgb);

                h += 32; 
            }

            if (pvMainContent.SelectedPage == pvpOrderList)
            {
                OrderOrderList(); //Reload also list of orders to reflect live data change
            }

            if (pvMainContent.SelectedPage == pvpLocationList)
            {
                LoadLocationList(); //Reload also list of orders to reflect live data change
            }
           
        }

        private void LoadSystem(RadPageViewPage pvp = null)
        {
            this.pvMenuSystem.Pages.Clear();
            if (pvp != null)
            {
                this.pvMenuSystem.SelectedPage = pvp;
            }

            ImageList = new IconLibrary();
            MenuClass = new MenuObject();

            Menu = MenuClass.MenuStructure();

                foreach (APC.Common.MenuSystem m in Menu.Where(x => x.Parent_ID == -1)) // -1 = main menu
                {

                    tree = new RadTreeView();
                    tree.Dock = DockStyle.Fill;
                    tree.AllowDragDrop = true;
                    tree.AllowDrop = false;
                    tree.ImageList = ImageList.Img16x16;
                   
                    tree.DoubleClick += MenuTree_DoubleClick;
                    tree.ItemDrag += new RadTreeView.ItemDragHandler(MenuTree_ItemDrag);
                    //tree.DragDrop += MenuTree_DragDrop;
                    //tree.DragEnding += MenuTree_DragEnding;

                    pv = new RadPageViewPage();

                    int i = 0;
                    i = ImageList.Img32x32.Images.IndexOfKey("neutral");

                    pv.Image = ImageList.Img32x32.Images[i];
                    pv.Controls.Add(tree);

                    RadTreeNode nd = new RadTreeNode(m.MenuText);
                    MenuObject o = new MenuObject();
                    o.Id = MenuClass.Id;
                    o.MenuType = MenuObject.eMenuType.TypeMenu;
                    o.MenuContext = MenuObject.MainMenu.MenuNonSpecific;
                    o.Expand = Convert.ToBoolean(m.ExpandMenu);
                    nd.Tag = o;

                    pv.Text = MenuClass.TranslateString(m.UILanguageID, this.UIlang); // TranslateUI(ui);
                
                    pvMenuSystem.Pages.Add(pv);

                    RecurciveMenu(m.ID, nd);

                    tree.Nodes.Add(nd);

                    if (m.ExpandMenu == true)
                    {
                        tree.ExpandAll();
                    }
                    else
                    {
                        tree.Nodes[0].Expand();
                    }

                    //Loop tree to set nodes to expand/Collapse according to propety in database
                    RecursiveTreenodes(tree.Nodes[0]);
                  
        
                }           
        }

        /// <summary>
        /// Loop all treenodes to collapse/expand according to menu property in dataabse "ExpandMenu"
        /// </summary>
        /// <param name="r"></param>
        private void RecursiveTreenodes(RadTreeNode r)
        {
            foreach (RadTreeNode rnd in r.Nodes)
            {
                if (rnd.Tag != null)
                {
                    if (rnd.Tag is MenuObject)
                    {
                        MenuObject o = (MenuObject)rnd.Tag;
                        if (o.Expand == true)
                        {
                            rnd.Expand();
                        }
                        else
                        {
                            rnd.Collapse();
                        }
                    }      
                }
                else
                {
                    rnd.Expand();
                }
                RecursiveTreenodes(rnd);
            }
        }

        private void ChangeControlsUI(String UIL)
        {
            //ctxSystem = new DataSystemDataContext();

            //foreach (CommandBarButton btn in cmdBarMenu.Items)
            //{
               
            //    if (ctxSystem != null)
            //    {
            //        foreach (UILanguage ui in ctxSystem.UILanguages.Where(x => x.ID == Convert.ToInt32(btn.Tag)))
            //        {
            //            switch (UIL)
            //            {
            //                case "dk-DK":
            //                    btn.Text = ui.dk_DK;
            //                    pvpNewOrder.Text = "Recept Detaljer";
            //                    pvpInfoBoard.Text = "Info Tavle";
            //                    mnuFile.Text = "File";
            //                    mnuHelp.Text = "Hjælp";
            //                    mnuWindows.Text = "Vinduer";
            //                    break;

            //                case "en-US":
            //                    btn.Text = ui.en_US;
            //                    pvpNewOrder.Text = "Recipe Details";
            //                    pvpInfoBoard.Text = "Info Board";
            //                    mnuFile.Text = "File";
            //                    mnuHelp.Text = "Help";
            //                    mnuWindows.Text = "Windows";
            //                    break;

            //                case "ko-KR":
            //                    btn.Text = ui.ko_KR;
            //                    pvpNewOrder.Text = "할꺼에요";
            //                    pvpInfoBoard.Text = "당신을 아";
            //                    mnuFile.Text = "할꺼에요";
            //                    mnuHelp.Text = "당신을 아";
            //                    mnuWindows.Text = "할꺼";
            //                    break;

            //            }
            //        }
            //    }
            //}
        }

        /// <summary>
        /// Adds all LocationTypes and Locations as Parent/Child to menu: Raw Material --> Locations in treeview
        /// </summary>
        /// <param name="nd"></param>
        /// <returns></returns>
        private void AddNodesLocations(RadTreeNode nd, MenuObject.MainMenu m)
        {
 
            RadTreeNode nLT;
            RadTreeNode nL;
            MenuObject o;

            Locations loc = new Locations(true);

            foreach (APC.Common.LocationsType lt in loc.LocationTypes)
            {

                o = new MenuObject();
                o.Id = lt.Id;
                o.MenuType = MenuObject.eMenuType.TypeLocationFolder;
                o.MenuContext = m;
                o.Expand = false;

                nLT = new RadTreeNode(lt.Name);
                nLT.Image = SetIcon("folder");
                nLT.Tag = o;

                foreach (APC.Common.Location l in loc.LocationList.Where(x => x.LocationTypeId == lt.Id))
                {
                    o = new MenuObject();
                    o.Id = l.Id;
                    o.MenuType = MenuObject.eMenuType.TypeLocation;
                    o.MenuContext = m; // MenuObject.MainMenu.MenuLocation; //Flag for load properties of selected Location on click in treeview (Menu system)
               
                   
                    nL = new RadTreeNode(l.Name);
                    nL.Tag = o;
                    nL.Image = SetIcon("silo");
                    nLT.Nodes.Add(nL);
                }

                nd.Nodes.Add(nLT);
            }
        }

        /// <summary>
        /// Adds all ...
        /// </summary>
        /// <param name="nd"></param>
        /// <returns></returns>
        private void AddNodesOrderHistory(RadTreeNode nd)
        {
            RadTreeNode nL;
            MenuObject mo;
            Order o = new Order(true);

            foreach (APC.Common.Order r in o.OrderList)
            {
                mo = new MenuObject();
                mo.Id = r.Id;
                mo.MenuType = MenuObject.eMenuType.TypeOrder;

                nL = new RadTreeNode(Convert.ToDateTime(r.EndDate).ToShortDateString() + " " + r.Name);
                nL.Tag = mo;
                nL.Image = SetIcon("order");
                nd.Nodes.Add(nL);
            }
        }

        /// <summary>
        /// Adds all ...
        /// </summary>
        /// <param name="nd"></param>
        /// <returns></returns>
        private void AddNodesReports(RadTreeNode nd)
        {
            RadTreeNode nL;
            MenuObject mo;
            Report r = new Report();

            foreach (APC.Common.Report report in r.ReportList)
            {
                mo = new MenuObject();
                mo.Tag = report.ReportRuntime;
                mo.Id = report.Id;
                mo.MenuType = MenuObject.eMenuType.TypeReport;

                nL = new RadTreeNode(report.Description);
                nL.Tag = mo;
                nL.Image = SetIcon("report");
                nd.Nodes.Add(nL);
            }
        }

        /// <summary>
        /// Adds all LocationTypes and Locations as Parent/Child to menu: Raw Material --> Locations in treeview
        /// </summary>
        /// <param name="nd"></param>
        /// <returns></returns>
        private void AddNodesRecipe(RadTreeNode nd)
        {
  
            RadTreeNode nL;
            MenuObject o;
            Recipe recipe = new Recipe();
           
            foreach (APC.Common.Recipe r in recipe.RecipeList)
                {
                   if (r.Id != 1)
                    {
                        o = new MenuObject();
                        o.Id = r.Id;
                        o.MenuType = MenuObject.eMenuType.TypeRecipe;

                        nL = new RadTreeNode(r.RecipeName);
                        nL.Tag = o;
                        nL.Image = SetIcon("recipe");
                        nd.Nodes.Add(nL);
                    }
                }
            //return root;
        }

        /// <summary>
        /// Adds all RawMaterials and RawMaterialGroups as Parent/Child to menu: Raw Material --> Material List in treeview
        /// </summary>
        /// <param name="nd"></param>
        /// <returns></returns>
        private void AddNodesRawMaterial(Int32 MenuId, RadTreeNode nd)
        {
            
            RadTreeNode nRMG;
            RadTreeNode nRM;
            MenuObject o;
            RawMaterials r;
            RawMaterials raw = new RawMaterials(true);


            foreach (RawMaterialGroup rmg in raw.RawMaterialGroups)
            {

                o = new MenuObject();
                o.Id = rmg.Id;
                o.MenuType = MenuObject.eMenuType.TypeMenu;
                o.ItemObject = rmg;
                o.Expand = false;

                nRMG = new RadTreeNode(rmg.Name);
                nRMG.Image = SetIcon("folder");
                nRMG.Tag = null;


                foreach (RawMaterial rm in raw.RawMaterialList.Where(x => x.RawMaterialGroupId == rmg.Id))
                {
                    r = new RawMaterials();
                    r.Id = rm.Id;

                    o = new MenuObject();
                    o.Id = rm.Id;
                    o.MenuType = MenuObject.eMenuType.TypeRawMaterial;
                    o.ItemObject = r;
                    o.Expand = false;

                    switch (MenuId) //RawMaterial is shown in both Raw Material menu and in Recipe menu. Therefore the context must be set
                    {
                        case 32:
                            o.MenuContext = MenuObject.MainMenu.MenuRawMaterial;
                            break;

                        case 34:
                            o.MenuContext = MenuObject.MainMenu.MenuRecipe;
                            break;
                    }
              
                    nRM = new RadTreeNode(rm.Name.Trim());
                    nRM.Tag = o;
                    nRM.Image = SetIcon("ingridient");
                    nRMG.Nodes.Add(nRM);
                }

                nd.Nodes.Add(nRMG);
                
            }      
        }

        /// <summary>
        /// Loads Menu + treeviews as Parent/Child in a recurcive loop
        /// </summary>
        /// <param name="Parent_ID"></param>
        private void RecurciveMenu(int Id, RadTreeNode nd)
        {

            foreach (MenuSystem mnu in this.Menu.Where(mnu => mnu.Parent_ID == Id).OrderBy(x => x.Sort))
            {
                RadTreeNode n = null;
                MenuObject o = null;

                n = new RadTreeNode();

                o = new MenuObject();
                o.Id = mnu.ID;
                o.MenuType = MenuObject.eMenuType.TypeMenu;
                o.MenuContext = MenuObject.MainMenu.MenuNonSpecific;
                o.Expand = Convert.ToBoolean(mnu.ExpandMenu);

                //TODO: cach all uilanguage records to not overload database on multiple loops
              
                 n.Text = MenuClass.TranslateString(mnu.UILanguageID, this.UIlang);


                n.Image = SetIcon(mnu.MenuIcon);
                n.Tag = o;

                nd.Nodes.Add(n);



                switch (mnu.ID)
                {
                    case 7:
                    AddNodesOrderHistory(n); 
                    break;

                    case 10:
                    AddNodesRecipe(n);
                    break;

                    case 13:
                    o.Expand = true;
                    AddNodesLocations(n, MenuObject.MainMenu.MenuRawMaterial);       
                    break;

                    case 32:
                    AddNodesRawMaterial(mnu.ID, n);       
                    break;

                    case 34:
                    AddNodesRawMaterial(mnu.ID, n);
                    break;

                    case 36:
                    AddNodesReports(n);
                    break;

                    case 45:
                    AddNodesLocations(n, MenuObject.MainMenu.MenuLocation);
                    break;

                }
                RecurciveMenu(mnu.ID, n);
            }
        }

        /// <summary>
        /// Returns icon based on icon name. E.g."folder"
        /// </summary>
        /// <param name="MenuIcon"></param>
        /// <returns></returns>
        private Image SetIcon(String MenuIcon = "")
        {
            int i;
            Image img = null;

            i = ImageList.Img16x16.Images.IndexOfKey(MenuIcon.Trim());

            if (i > -1)
            {
                img = ImageList.Img16x16.Images[i];
            }
            return img;
        }

        /// <summary>
        /// Translates UI Language 
        /// </summary>
        /// <param name="Lang"></param>
        /// <returns></returns>
        private String TranslateUI(UILanguage Lang)
        {
            string Lng = null;

            switch (this.UIlang)
            {
                case "en-US":
                    Lng = Lang.en_US;
                    break;

                case "dk-DK":
                    Lng = Lang.dk_DK;
                    break;

                case "ko-KR":
                    Lng = Lang.ko_KR;
                    break;
            }
            return Lng;
        }

        /// <summary>
        /// Returns the TagListe.Id on a given VarName
        /// </summary>
        /// <param name="TagName"></param>
        /// <returns></returns>
        //private int GetTagIdOnTagName(String TagName)
        //{
        //    int TagListeID = 0;

        //    if (TagList == null) //Test if all Tags is already loaded, if not, they must be loaded
        //    {
        //        TagList = new List<APC.Common.TagListe>();
        //        Tag tg = new Tag(true);
        //        TagList = tg.TagList;
        //    }

   
        //    //var query = from i in ctx.TagListes
        //    //            where i.VarName == TagName
        //    //            select i;

        //    //foreach (var id in query)
        //    //{
        //    APC.Common.TagListe tag = TagList.Where(x => x.VarName == TagName).FirstOrDefault();
        //    //}

        //    return tag.Id; // TagListeID;
        //}

        /// <summary>
        /// Loads pair of TagNames and its value
        /// </summary>
        /// <param name="TagNamePart">Search on part of tagname to find its Id</param>
        /// <param name="TagValue">The value to send with tagname</param>
        /// <param name="BatchCountId">Each TagName + Value is related to a BatchCountId (1, 2, 3 ...)</param>
        /// <returns></returns>
        //private TagValuePair LoadTagValuePair(String TagNamePart, String TagValue, int BatchCountId)
        //{

        //    TagValuePair tvp = null;

        //    //Fill List with all tags on first run...
        //    if (this.TagListFull == null)
        //    {
        //        var q = from var3 in ctx.TagListes.Where(str => str.AddToTransaction == 1 && str.ToZenonRead == 0)
        //                    select var3;
        //        TagListFull = q.ToList<APC.Common.TagListe>();
        //    }

        //    //Filter on part of Tagname
        //    var query = TagListFull.Single(x => x.VarName.EndsWith(TagNamePart));
        
        //        tvp = new TagValuePair();
        //        tvp.TagListeId = query.Id;
        //        tvp.TagName = query.VarName;
        //        tvp.TagValue = TagValue;
               
             
        //    return tvp;
        //}

        /// <summary>
        /// Loads calculated Batch list for an Order
        /// </summary>
        /// <param name="OrderNumber"></param>
        /// <param name="Quantum"></param>
        /// <param name="BatchSize"></param>
        private void ValidateOrder(String OrderNumber, Int64 Quantum, Int64 BatchSize)
        {
            this.lstBatch.Items.Clear();
          
            ListViewDataItem lst;
            Batch bt;
            int a = 0;
 
            int BatchCount = Convert.ToInt16((Quantum / BatchSize)); //Divide Batch size with quantum to get number of batches to run
            Int64 BatchRemainder = (Quantum % BatchSize); //When dividing with odd number a remainder is returned. Last batch size is equal to the remainder

            Recipe rcp = new Recipe(this._RecipeId);

            if (rcp.RawMaterialNegativeList != null)
            {
                //Find this orders OrderSequence number
                Order o = new Order();
               // o.LoadLastOrderIngridients();
                
                decimal NumberOfBatches = o.NumberOfBatches;
                int BatchFlush = 0;
                bool ContaminationRisk = false;
                OrderContaminationInfo coi;
    
                //Do contamination check per ingridient in negative list!
                foreach (RawMaterials r in rcp.RawMaterialNegativeList)
                {
                    BatchFlush = r.BatchFlush;

                    coi = o.CheckContamination(r.Id, BatchFlush);
                    if (coi != null)
                    {
                        ValidationSetStatusMessages(OrderStatusScope.TypeOrderContamination, OrderStatusType.TypeError, coi.OrderNumber + " " + coi.OrderName + " on " + coi.RawMaterialNumber + " " + coi.RawMaterialName);
                        ValidationMessagesCount += 1;
                    }
                }   
            }


            List<Decimal> BatchAmount = new List<Decimal>(); //Each item in list holds amount per batch
            for (int x = 0; x < BatchCount; x++)
            {
                BatchAmount.Add(BatchSize);
            }
            if (BatchRemainder > 0)
            {
                BatchAmount.Add(BatchRemainder);

                if (BatchRemainder < Convert.ToInt16(txtOrderMinBatchSize.Text))
                {
                    ValidationSetStatusMessages(OrderStatusScope.TypeMinBatchSize, OrderStatusType.TypeAlert);
                    ValidationMessagesCount += 1;
                    btnSendToProduction.Enabled = false;
                }

            }

            string SiloArray = "";
            int StorageItems = 1;
            APC.Common.Location l;

            foreach (RadListDataItem ri in lstOrderStorage.Items)
            {
                l = (APC.Common.Location)ri.Tag;

                SiloArray += l.LocationPosition.ToString() + ((StorageItems != lstOrderStorage.Items.Count) ? "," : "");
                StorageItems += 1;
            }

            foreach (Decimal d in BatchAmount) // Loop each Batch
            {
              
                bt = new Batch();
                bt.BacthCountNumber = a + 1;
                bt.OrderId = this._OrderId;
                bt.BatchNumber = OrderNumber + "-" + (a + 1 ).ToString("0000");
                bt.SendToZenon = 0;
                bt.ZenonControlId = 4;
                bt.Status = 0;


                Tag tag = new Tag(); //Handles load of all tags + values

                //Load values to set in TagValuePairs
                tag.OrderId = this._OrderId.ToString();
                tag.OrderNumber = this.txtOrderNumber.Text.Trim();
                tag.BatchNumber = OrderNumber + "-" + (a + 1).ToString("0000");
                tag.BatchCounter = (a + 1);
                tag.BatchId = a.ToString();
                tag.RecipeName = rcp.RecipeName;
                tag.RecipeNumber = rcp.RecipeNumber;
                tag.TotalBatchCount = BatchAmount.Count;
                tag.StorageSiloArray = SiloArray;

                Tag t = new Tag();
                List<APC.Common.TagListGroup> lstTagListGroups = t.LoadTagListGroup().Where(x => x.GroupNo != 30000).ToList();

                //Loop locations in order to send data or "no data" for each location
                foreach (APC.Common.TagListGroup tlg in lstTagListGroups)
                {
                        //Find ingridients related to recipe on tlg.Id
                    List<APC.RawMaterials> ingridients = rcp.RawMaterialList.Where(x => x.TagListeGroupId == tlg.Id).ToList<APC.RawMaterials>();

                        tag.TagListeGroupId = tlg.Id;
                        tag.PacketSize = (ingridients.Count == 0) ? -1 : ingridients.Count;
                        tag.SetTagHeader(); //Write header tags per taglistgroup per batch

                        //Loop each ingredient and load tags with values
                        foreach (APC.RawMaterials i in ingridients)
                        {
                            Decimal amount = (Convert.ToInt64(i.AmountProcent) * BatchAmount[a] / 100); //Calculated amount 

                            tag.TagGroupSilo(Convert.ToInt16(tlg.GroupNo), i, amount); 
                            
                        }
                }

                bt.TagValuePairs = tag.TagValuePairs; //Add collection of TagNames + TagValues to property of Batch collection (like: "APC_PLC_SCALE_SILO_NO_1" value 
                tag.TagValuePairs = null; //Reset TagValuePairs (next batch in loop will initiate new collect of keyvaluepairs...)

                lst = new ListViewDataItem();
                lst.Tag = bt;
                lst.Image = SetIcon("process");
                lst.SubItems.Add("");
                lst.SubItems.Add((a + 1).ToString());
                lst.SubItems.Add(rcp.RecipeName);
                lst.SubItems.Add(d.ToString());  //lst.SubItems.Add(BatchAmount[a].ToString());

                lstBatch.Items.Add(lst);
                a++;
                BatchCounter++;
            }

            //Add sum
            lst = new ListViewDataItem();
            lst.Tag = null;
            lst.BackColor = Color.LightGray;
            lst.BackColor2 = Color.White;
            lst.Font = new Font(this.Font, FontStyle.Bold);
            lst.SubItems.Add("");
            lst.SubItems.Add("");
            lst.SubItems.Add("TOTAL");
            lst.SubItems.Add(Quantum.ToString());
            lstBatch.Items.Add(lst);

            
        }

        /// <summary>
        /// Loads Ingredients list for selected Recipe or Ordre
        /// </summary>
        /// <param name="Quantum"></param>
        private void LoadRecipeIngredientList()
        {

            ListViewDataItem lst;
            double ProcentCount = 0;
            lstRecipeIngredients.Items.Clear();

            RawMaterials rm;

                foreach (APC.RawMaterials r in ListIngridients)
                {
                    lst = new ListViewDataItem();
                    lst.Tag = r;
                    lst.Image = SetIcon("ingridient");
                    lst.BackColor = SetBackColor(r.ColorMap);
                    lst.BackColor2 = lst.BackColor;
                    lst.ForeColor = Color.Black; //Default
                    lst.Font = new Font(this.Font, FontStyle.Regular);
                    lst.SubItems.Add("");
                    lst.SubItems.Add(r.Number);
                    lst.SubItems.Add(r.Name);
                    lst.SubItems.Add(r.AmountProcent.ToString("N2"));
                    lst.SubItems.Add(r.Tolerance);
                    
                    if (r.LocationName == null)
                    {
                        lst.SubItems.Add("Select Location");
                    }
                    else
                    {
                        lst.SubItems.Add(r.LocationName);
                    }

                    lstRecipeIngredients.Items.Add(lst);

                    ProcentCount = ProcentCount + Convert.ToInt64(r.AmountProcent);
                }


                //Add Sum...
                lst = new ListViewDataItem();

                rm = new RawMaterials();
                rm.Id = -1;
                rm.RecipeId = -1;
                rm.ItemType = RawMaterials.eItemType.TypeSum;
                rm.IsSaved = true;



                if (ProcentCount > 100 || ProcentCount < 100 && ProcentCount != 0) //Color red for no compliance...
                {
                    lst.BackColor = Color.Red;
                    lst.BackColor2 = Color.White;
                }
                else
                {
                    lst.BackColor = Color.LightGray;
                    lst.BackColor2 = Color.White;
                }

                lst.Tag = rm;
                lst.Font = new Font(this.Font, FontStyle.Bold);
                lst.SubItems.Add("");
                lst.SubItems.Add("");
                lst.SubItems.Add("");
                lst.SubItems.Add(ProcentCount.ToString("N2") + "%");


                lstRecipeIngredients.Items.Add(lst);

            
        }

        /// <summary>
        /// Loads Ingredients list for selected Recipe or Ordre
        /// </summary>
        /// <param name="Quantum"></param>
        private void LoadOrderIngredientList(Int64 Quantum = 0)
        {
     
            ListViewDataItem lst;
            double ProcentCount = 0;
            double QuantumTotal = 0;
            double QuantumPerIngridient = 0;
            decimal QuantumTolerancePerIngridient = 0;
            RawMaterials rm;
            lstOrderRecipeIngridients.Items.Clear();


            if (_RecipeId != 0)
            {
                foreach (APC.RawMaterials r in ListIngridients.OrderBy(x => x.TagListeGroupId))
                {

                    lst = new ListViewDataItem();
                    lst.Tag = r;
                    lst.Image = SetIcon("ingridient");
                    lst.BackColor = SetBackColor(r.ColorMap);
                    lst.BackColor2 = lst.BackColor;
                    lst.ForeColor = Color.Black; //Default
                    lst.Font = new Font(this.Font, FontStyle.Regular);
                    lst.SubItems.Add("");
                    lst.SubItems.Add(r.Number);
                    lst.SubItems.Add(r.Name);
                    lst.SubItems.Add(r.AmountProcent.ToString("N2"));
                    
                    
                    if (Quantum > 0) //Total order Amount must be summerized and tolerence calculated per ingridient
                    {
                        //Calculated set point in kg based on procent
                        QuantumPerIngridient = Convert.ToDouble((r.AmountProcent * Quantum) / 100);
                        lst.SubItems.Add(QuantumPerIngridient);
                        lst.SubItems.Add(r.Tolerance);

                        //Calculated tolerence in kg based on tolerence procent
                        QuantumTolerancePerIngridient = Convert.ToDecimal((Convert.ToDecimal(QuantumPerIngridient) * r.Tolerance) / 100);
                        lst.SubItems.Add(QuantumTolerancePerIngridient);

                        //Total sum for footer
                        QuantumTotal = QuantumTotal + Convert.ToDouble(lst.SubItems[4]);
                    }
                    else
                    {

                        lst.SubItems.Add(0); //Calculated amount in kg
                        lst.SubItems.Add(r.Tolerance);
                        lst.SubItems.Add(0);
                    }

                    lst.SubItems.Add(r.LocationName);
                    lstOrderRecipeIngridients.Items.Add(lst);
                    
                    ProcentCount = ProcentCount + Convert.ToInt64(r.AmountProcent); 
                }


                //Add Sum...
                lst = new ListViewDataItem();

                rm = new RawMaterials();
                rm.Id = -1;
                rm.RecipeId =-1;
                rm.ItemType = RawMaterials.eItemType.TypeSum;
                rm.IsSaved = true;

               

                if (ProcentCount > 100 || ProcentCount < 100 && ProcentCount != 0) //Color red for no compliance...
                {
                    lst.BackColor = Color.Red;
                    lst.BackColor2 = Color.White;
                }
                else
                {
                    lst.BackColor = Color.LightGray;
                    lst.BackColor2 = Color.White;
                }

                lst.Tag = rm;
                lst.Font = new Font(this.Font, FontStyle.Bold);
                lst.SubItems.Add("");
                lst.SubItems.Add("");
                lst.SubItems.Add("");
                lst.SubItems.Add(ProcentCount.ToString() + "%");
                lst.SubItems.Add(QuantumTotal.ToString());

                lstOrderRecipeIngridients.Items.Add(lst);

            }

         
        }

        #region Tree Menu Handler

        /// <summary>
        /// Clear form fields for preparing new Raw Material
        /// </summary>
        private void ClearRawMaterial()
        {
            this.txtRawMaterialName.Text = "";
            this.txtRawMaterialNumber.Text = "";
            this.txtRawMaterialDensity.Text = "";
            this.cmbRawMaterialGroup.Text = "Select Group";
            _SaveAction = SaveAction.TypeNew;

            lstLocation.Items.Clear();
        }

        /// <summary>
        /// Clear all fields befor add new Recipe
        /// </summary>
        private void ClearRecipe()
        {
            this.txtRecipeName.Text = "";
            this.txtRecipeNote.Text = "";
            this.txtRecipeNumber.Text = "";
            this.txtRecipeEndProductName.Text = "";
            this.txtDefaultQuantum.Text = "100";
            this.txtRecipeMinBatch.Text = "100";
            this.txtRecipeRecBatchSize.Text = "100";
            this.lstRecipeIngredients.Items.Clear();

            _SaveAction = SaveAction.TypeNew;
        }

        private void RawMaterialAddNew()
        {

            if (pvMainContent.SelectedPage != pvpRawMaterial)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpRawMaterial);
            }

            if (cmbRawMaterialGroup.DataSource == null)
            {
                RawMaterials rm = new RawMaterials();
                List<APC.Common.RawMaterialGroup> RawMaterialGroups;
                RawMaterialGroups = rm.RawMaterialGroups;

                //Combobox: Select Group
                this.cmbRawMaterialGroup.ValueMember = "Id";
                this.cmbRawMaterialGroup.DisplayMember = "Name";
                this.cmbRawMaterialGroup.DataSource = RawMaterialGroups;
            }
            ClearRawMaterial();

        }

        private void RecipeAddNew()
        {
            if (pvMainContent.SelectedPage != pvpRecipe)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpRecipe);
            }

            pvRecipe.SelectedPage = pvpIngridients;

            lstBatch.Items.Clear();
            lstRecipeNegativeList.Items.Clear();
            ListIngridients = new List<RawMaterials>();
            ListNegativeRawMaterials = new List<RawMaterials>();
          
            ClearRecipe();

            btnMakeOrder.Enabled = false;

            //Add sum item
            //RawMaterials rm = new RawMaterials();
            //rm.Id = -1;
            //rm.ItemType = RawMaterials.eItemType.TypeSum;

            //ListViewDataItem lst = new ListViewDataItem();
            //lst.Tag = rm;
            //lst.BackColor = Color.LightGray;
            //lst.BackColor2 = Color.White;
            //lst.Font = new Font(this.Font, FontStyle.Bold);
            //lst.SubItems.Add("");
            //lst.SubItems.Add("");
            //lst.SubItems.Add("");
            //lst.SubItems.Add("0");
            //lst.SubItems.Add("0");

            //lstRecipeIngredients.Items.Add(lst);

        }

        /// <summary>
        /// Load recipe list
        /// </summary>
        private void LoadRecipeList()
        {
            if (pvMainContent.SelectedPage != pvpRecipeList)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpRecipeList);
            }

            lstRecipeList.Items.Clear();
            List<APC.Common.Recipe> RecipeList;

            Recipe r = new Recipe();
            RecipeList = r.RecipeList;
     
                foreach (APC.Common.Recipe re in RecipeList)
                {
                    ListViewDataItem lst = new ListViewDataItem();
                    lst.Tag = re.Id;
                    lst.Image = SetIcon("recipe");
                    lst.SubItems.Add(""); //Icon
                    lst.SubItems.Add(re.RecipeName);
                    lst.SubItems.Add(re.RecipeNumber);
                    lst.SubItems.Add(re.EndProductName);
                    lst.SubItems.Add(re.RecBatchSize.ToString());
                    lst.SubItems.Add(re.MinBatchSize.ToString());
                    lst.SubItems.Add(re.DefaultOrderQuantum.ToString());
                   
                    lstRecipeList.Items.Add(lst);
                }
            }

        /// <summary>
        /// Change tabpage + clear form fields
        /// </summary>
        private void OrderHandlingNewOrder()
        {

            if (pvMainContent.SelectedPage != pvpOrder)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpOrder);
            }

            lstOrderStorage.Items.Clear();
            lstOrderRecipeIngridients.Items.Clear();
            lstStatus.Items.Clear();

            btnEditOrder.Visible = false;
            btnValidateOrder.Enabled = false;
            btnSendToProduction.Enabled = false;
            btnEditOrder.Visible = false;
            btnAddStorageLocation.Enabled = true;
            btnRemoveStorageLocation.Enabled = true;

            Order o = new Order();

            this.txtOrderNumber.Text = o.GetNextOrderNumber();
            this._OrderPostfixNumber = o.OrderPostfixNumber;


            this.txtRecipe.Text = "Select Recipe";
           
            pvpOrder.Text = "New Order: " + this.txtOrderNumber.Text;
            txtOrderQuantum.Text = "0";
            txtRecBatchSize.Text = "0";
            txtEndProductName.Text = "";

            lstOrderStorage.Items.Clear();
            lstOrderStorage.Height = 20;

        }

        /// <summary>
        /// Load pending and running order list
        /// </summary>
        private void OrderOrderList()
        {
            if (pvMainContent.SelectedPage != pvpOrderList)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpOrderList);
            }

            lstActiveOrderList.Items.Clear();

            Order o = new Order(true); //Loads active orders

            foreach (APC.Common.Order order in o.ActiveOrderList)
            {
            
                ListViewDataItem lst = new ListViewDataItem();
                lst.Tag = order.Id;
                lst.Image = SetIcon("order");
                lst.SubItems.Add(""); //Icon
                lst.SubItems.Add(order.OrderSequence.ToString());
                lst.SubItems.Add(order.OrderNumber);
                lst.SubItems.Add(order.Name);
                lst.SubItems.Add(order.Recipe.RecipeNumber);
                lst.SubItems.Add(order.Recipe.RecipeName);
                lst.SubItems.Add(order.Amount.ToString());
                lst.SubItems.Add(order.StartDate);
                lst.SubItems.Add(order.EndDate);

                switch (order.OrderState)
                {
                    case 0:
                        lst.SubItems.Add("locked");
                        break;

                    case 1:
                        lst.SubItems.Add("pending");
                        break;

                    case 2:
                        lst.SubItems.Add("in process");
                        break;

                }

                //if (order.StartDate != null)
                //{
                //    lst.SubItems.Add("in process");
                //}
                //if (order.EndDate != null)
                //{
                //    lst.SubItems.Add("finished");
                //}
                //if (order.StartDate == null && order.EndDate == null)
                //{
                //    lst.SubItems.Add("pending");
                //}
              
                lstActiveOrderList.Items.Add(lst);
            }    
        
        }

        /// <summary>
        /// Load pending and running order list
        /// </summary>
        private void LoadLocationList()
        {
            if (pvMainContent.SelectedPage != pvpLocationList)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpLocationList);
            }

            foreach (ListViewDataItem lstv in lstLocationList.Items)
            {
                lstv.Group = null;
            }
            lstLocationList.Groups.Clear(); 

            Locations l  = new Locations(true); //Loads active orders
            RawMaterials r = new RawMaterials();

            List<RawMaterialOnLocation> lstRawMaterial;
            
            lstRawMaterial = r.LoadRawMaterialOnLocationList();

            string RawMaterialName = "";
            string RawMaterialNumber = "";

            ListViewDataItemGroup lstGrp;

            foreach (LocationsType lt in l.LocationTypes)
            {
                lstGrp = new ListViewDataItemGroup(lt.Name.Trim());
                lstLocationList.Groups.Add(lstGrp);


                foreach (Location loc in l.LocationList.Where(x => x.LocationTypeId == lt.Id))
                {

                    var q = (from raw in lstRawMaterial
                             where raw.LocationId == loc.Id
                             select raw).FirstOrDefault();

                    if (q != null)
                    {
                        RawMaterialName = q.RawMaterialName;
                        RawMaterialNumber = q.RawMaterialNumber;
                    }
                    else
                    {
                        RawMaterialName = "";
                        RawMaterialNumber = "";
                    }


                    ListViewDataItem lst = new ListViewDataItem();
                    lst.Tag = loc.Id;
                    lst.Image = SetIcon("silo");
                    lst.SubItems.Add(""); //Icon
                    lst.SubItems.Add(loc.Name);
                    lst.SubItems.Add(loc.MaxVolume.ToString());
                    lst.SubItems.Add(loc.MinVolume.ToString());
                    lst.SubItems.Add(loc.Volume.ToString());
                    lst.SubItems.Add(RawMaterialNumber);
                    lst.SubItems.Add(RawMaterialName);
                    if (loc.Volume < 0)
                    {
                        lst.ForeColor = Color.Red;
                    }
                    lstLocationList.Items.Add(lst);
                    lst.Group = lstGrp;
                    lstLocationList.SelectedItem = lst;
                }
            }
            
        }

        private void RawMaterialList()
        {
            if (pvMainContent.SelectedPage != pvpRawMaterialList)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpRawMaterialList);
                this.LoadRawMaterialList();
            }
        }

        #endregion

        /// <summary>
        /// Loads full list of all raw materials
        /// </summary>
        private void LoadRawMaterialList()
        {

            if (RawMaterialIsLoaded == false)
            {

                foreach (ListViewDataItem lstv in lstRawMaterial.Items)
                {
                    lstv.Group = null;
                }
                lstRawMaterial.Groups.Clear(); 

                lstRawMaterial.Items.Clear();

                List<RawMaterial> RawMaterialList;
                List<RawMaterialGroup> RawMaterialGroup;

                RawMaterials rm = new RawMaterials();

                RawMaterialList = rm.RawMaterialList;
                RawMaterialGroup = rm.RawMaterialGroups;

                ListViewDataItemGroup lstGrp;

                foreach (var rmg in RawMaterialGroup)
                {
                    lstGrp = new ListViewDataItemGroup(rmg.Name.Trim());
                    lstRawMaterial.Groups.Add(lstGrp);

                    foreach (var r in RawMaterialList.Where(x => x.RawMaterialGroupId == rmg.Id && x.Active == true))
                    {
                
                        ListViewDataItem lst = new ListViewDataItem();
                        lst.Tag = r.Id;
                        lst.Image = SetIcon("ingridient");
                        lst.SubItems.Add(""); //Icon
                        lst.SubItems.Add(r.MaterialNumber);
                        lst.SubItems.Add(r.Name);
                        lst.SubItems.Add(r.Density);
                        lst.SubItems.Add("0");
                        lst.SubItems.Add(rmg.Name);

                        lstRawMaterial.Items.Add(lst);
                        lst.Group = lstGrp;
                    }
                }
                RawMaterialIsLoaded = true;
            }

        }

        private void ShowReport(MenuObject m)
        {
            string GetReportByName = m.Tag.ToString();
            string ReportPath = "";
            string ReportRuntimeFile = "";
    
            ReportPath = Settings.Default.ReportPath;
            ReportRuntimeFile = ReportPath + GetReportByName + ".DLL";

            Assembly rptAssembly = Assembly.LoadFile(@"" + ReportRuntimeFile);

            Type rptType = rptAssembly.GetType(GetReportByName + ".Report1");

            object rptInstance = Activator.CreateInstance(rptType);

            PropertyInfo ConnectionPropertyInfo = rptType.GetProperty("SetConnectionString", BindingFlags.Public | BindingFlags.Instance);

            string cnString = ConfigurationManager.ConnectionStrings["APC.Properties.Settings.APC_DataConnection"].ConnectionString; 
            ConnectionPropertyInfo.SetValue(rptInstance, cnString, null);

            //ConnectionPropertyInfo.SetValue(rptInstance, "Data Source=VSRV1;Initial Catalog=Andritz_APC;Persist Security Info=True;User ID=sa;Password=Weekend1519", null);

            //If user cancel filter the report viewer is not shown
            rptType.InvokeMember("OpenRepDialog", BindingFlags.Default | BindingFlags.InvokeMethod, null, rptInstance, null);


            PropertyInfo myProperties = rptType.GetProperty("RunReport", BindingFlags.Public | BindingFlags.Instance);
            object[] hjO = new object[0];

            object hjRes = myProperties.GetValue(rptInstance, hjO);
            bool RunReportNow = (bool)hjRes;
            if (RunReportNow == true)
            {
                Telerik.Reporting.Report rpt = (Telerik.Reporting.Report)rptInstance;
                this.rpReportViewer.Report = rpt;
                rpReportViewer.RefreshReport();

                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpReport);
            }
        }

        /// <summary>
        /// Loads a saved order
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="LoadInfoBoard"></param>
        private void LoadOrder(Int32 Id)
        {
            if (pvMainContent.SelectedPage != pvpOrder)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpOrder);
            }

            lstStatus.Items.Clear();
            this._SaveAction = SaveAction.TypeEdit;

            Order o = new Order(Id);
            this._OrderId = Id;
            this._RecipeId = o.RecipeId;

            btnEditOrder.Visible = true;
            txtOrderNumber.ReadOnly = true;
            txtOrderQuantum.ReadOnly = true;
            txtRecipe.ReadOnly = true;
            btnBrowseRecipes.Enabled = false;
            txtEndProductName.ReadOnly = true;
            txtRecBatchSize.ReadOnly = true;
            txtOrderMinBatchSize.ReadOnly = true;
            //lstOrderStorage.Enabled = false;
            btnValidateOrder.Enabled = false;
            btnSendToProduction.Enabled = false;
            btnAddStorageLocation.Enabled = false;
            btnRemoveStorageLocation.Enabled = false;

            if (o.IsInProduction == true)
            {
                ValidationSetStatusMessages(OrderStatusScope.TypeOrderRunning, OrderStatusType.TypeOK, o.OrderNumber + " " + o.Name);
                btnEditOrder.Enabled = false;         
            }
            else
            {
                //o.SetOrderState(Order.OrderState.NotReady); //Lock the order for Bridge/Zenon
                btnEditOrder.Enabled = true;  
            }

            RadListDataItem ri;
            lstOrderStorage.Items.Clear();
           


            if (o.StorageLocationList != null)
            {
                foreach (APC.Common.Location l in o.StorageLocationList)
                {
                    ri = new RadListDataItem();
                    ri.Tag = l;
                    ri.Text = l.Name;
                    lstOrderStorage.Items.Add(ri);
                }
                lstOrderStorage.Height = lstOrderStorage.Items.Count * 20;
            }

            Recipe r = new Recipe();

            pvpOrder.Text = o.Name;
            txtOrderNumber.Text = o.OrderNumber;
            txtOrderMinBatchSize.Text = o.RecommendedBatchSize.ToString();
            txtOrderQuantum.Text = o.OrderQuantum.ToString();
            txtOrderQuantum.Tag = o.OrderQuantum.ToString(); //Remembers value, to later determine if user has changed this

            Int64 Quantum = o.OrderQuantum;

            Recipe rcp = new Recipe(o.RecipeId);

            this.btnValidateOrder.Tag = rcp; //Use this recipe object in btnCalculateBatches_Click if user later changes values of quantum 
            this.txtRecipe.Text = rcp.RecipeName;
            this.txtRecipe.Tag = o.RecipeId;
            this.txtRecBatchSize.Text = rcp.RecBatchSize.ToString();
            this.txtRecBatchSize.Tag = rcp.RecBatchSize.ToString(); //Remembers value, to later determine if user has changed this
            this.txtEndProductName.Text = rcp.EndProductName;

            ListViewDataItem lst;
            Locations loc;
            lstOrderRecipeIngridients.Items.Clear();
            Decimal OrderQuantumProcent = 0;
            Decimal QuantumTolerance = 0;
            Decimal ProcentCount = 0;
            Decimal QuantumTotal = 0;

            ListIngridients = o.IngredientList;

            foreach (APC.RawMaterials i in ListIngridients)
            {
                loc = new Locations(Convert.ToInt16(i.LocationId));

                OrderQuantumProcent = Convert.ToDecimal((o.OrderQuantum * i.AmountProcent) / 100);
                QuantumTolerance =  Convert.ToDecimal((OrderQuantumProcent * Convert.ToDecimal(i.Tolerance)) / 100);
                ProcentCount += Convert.ToDecimal(i.AmountProcent);
                QuantumTotal += OrderQuantumProcent;

                lst = new ListViewDataItem();
                lst.Tag = i;
                lst.Image = SetIcon("ingridient");
                lst.BackColor = SetBackColor(loc.ColorMap);
                lst.BackColor2 = lst.BackColor;
                lst.ForeColor = Color.Black; //Default
                lst.Font = new Font(this.Font, FontStyle.Regular);
                lst.SubItems.Add("");
                lst.SubItems.Add(i.Number);
                lst.SubItems.Add(i.Name);
                lst.SubItems.Add((i.AmountProcent).ToString("N2"));
                lst.SubItems.Add(OrderQuantumProcent.ToString("N2"));
                lst.SubItems.Add((Convert.ToDecimal(i.Tolerance)).ToString("N2"));
                lst.SubItems.Add(QuantumTolerance.ToString("N2"));
                lst.SubItems.Add(i.LocationName);
                lstOrderRecipeIngridients.Items.Add(lst);

            }

            //Add Sum...
            lst = new ListViewDataItem();

            if (ProcentCount > 100 || ProcentCount < 100 && ProcentCount != 0) //Color red for no compliance...
            {
                lst.BackColor = Color.Red;
                lst.BackColor2 = Color.White;
            }
            else
            {
                lst.BackColor = Color.LightGray;
                lst.BackColor2 = Color.White;
            }

            lst.Tag = null;
            lst.Font = new Font(this.Font, FontStyle.Bold);
            lst.SubItems.Add("");
            lst.SubItems.Add("");
            lst.SubItems.Add("");
            lst.SubItems.Add(ProcentCount.ToString("N2") + "%");
            lst.SubItems.Add(QuantumTotal.ToString("N2"));

            lstOrderRecipeIngridients.Items.Add(lst);



        }
       
        /// <summary>
        /// Loads details + ingridients of the recipe
        /// </summary>
        /// <param name="Id"></param>
        private void LoadRecipe(Int32 Id)
        {

            if (pvMainContent.SelectedPage != pvpRecipe) //Set the correct tabpage
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpRecipe);
            }

            pvRecipe.SelectedPage = pvpIngridients;

          
            this._RecipeId = Id;
            this._SaveAction = SaveAction.TypeEdit;
            btnMakeOrder.Enabled = true;

            Recipe rcp = new Recipe(Id);

            this.txtRecipeName.Text = rcp.RecipeName;
            this.txtRecipeNumber.Text = rcp.RecipeNumber;
            this.txtRecipeEndProductName.Text = rcp.EndProductName;
            this.txtDefaultQuantum.Text = rcp.DefaultOrderQuantum.ToString();
            this.txtRecipeRecBatchSize.Text = rcp.RecBatchSize.ToString();
            this.txtRecipeMinBatch.Text = rcp.MinBatchSize.ToString();
            this.txtRecipeNote.Text = rcp.Note;

            RawMaterials raw = new RawMaterials();

            lstRecipeNegativeList.Items.Clear();

            ListNegativeRawMaterials = new List<RawMaterials>();
            
            //List negativ raw materials
            foreach (RawMaterials rd in rcp.RawMaterialNegativeList)
            {
                    //rd.RecordStatus = RawMaterials.eRecordStatus.IsNotChanged;
                    ListNegativeRawMaterials.Add(rd);

                    ListViewDataItem lst = new ListViewDataItem();
                    lst.Tag = rd;
                    lst.Image = SetIcon("ingridient");
                    lst.SubItems.Add(""); //Icon     
                    lst.SubItems.Add(rd.Number);
                    lst.SubItems.Add(rd.Name);
                    lst.SubItems.Add(rd.BatchFlush.ToString()); //Flush is number of 'clean' batches to run to avoid contamination of the recipe

                    lstRecipeNegativeList.Items.Add(lst);
            }

            ListIngridients = rcp.RawMaterialList;

            LoadRecipeIngredientList();
        }

        /// <summary>
        /// Loads selected RawMaterial properties
        /// </summary>
        /// <param name="Id"></param>
        private void LoadRawMaterial(Int32 Id)
        {

            if (pvMainContent.SelectedPage != pvpRawMaterial)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpRawMaterial);
            }
            lstLocation.Items.Clear();
            lstRecipeNegativeList.Items.Clear();

            //Flag for editing existing Raw Material
            this._ObjectID = Id;
            this._RawMaterialId = Id;
            this._SaveAction = SaveAction.TypeEdit;

            RawMaterials rm = new RawMaterials(Id);
            RawMaterielLocation rml;

            this.txtRawMaterialName.Text = rm.Name.Trim();
            this.txtRawMaterialNumber.Text = rm.Number.Trim();
            this.txtRawMaterialDensity.Text = rm.Density.Trim();
          
            List<APC.Common.GetRawMaterialLocationsResult> RawMaterialLocations;
            RawMaterialLocations = rm.RawMaterialLocations;

            //List related locations for selected Raw Material
            foreach (var r in RawMaterialLocations)
            {
                rml = new RawMaterielLocation();
                rml.IsSaved = true;
                rml.LocationId = r.Id1;
                rml.RawMaterilaId = Id;

                ListViewDataItem lst = new ListViewDataItem();
                lst.Tag = rml;
                lst.ImageKey = "silo";
                lst.SubItems.Add(""); //Icon     
                lst.SubItems.Add(r.LTName);
                lst.SubItems.Add(r.Name);

                lstLocation.Items.Add(lst);
            }

            if (cmbRawMaterialGroup.DataSource == null)
            {
                List<APC.Common.RawMaterialGroup> RawMaterialGroups;
                RawMaterialGroups = rm.RawMaterialGroups;

                //Combobox: Select Group
                this.cmbRawMaterialGroup.ValueMember = "Id";
                this.cmbRawMaterialGroup.DisplayMember = "Name";
                this.cmbRawMaterialGroup.DataSource = RawMaterialGroups;
            }
            this.cmbRawMaterialGroup.SelectedValue = Convert.ToInt32(rm.GroupId);

        }

        /// <summary>
        /// Loads selected Location for editing or viewing properties
        /// </summary>
        /// <param name="LocationId"></param>
        private void LoadLocationEdit(Int32 LocationId)
        {
            if (pvMainContent.SelectedPage != pvpDefault)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpDefault);
            }

            this._LocationId = LocationId;
            Locations loc = new Locations(LocationId);

            this.txtLocationName.Text = loc.LocationName;
            this.txtMaxVolume.Text = loc.MaxVolume.ToString();
            this.txtMinVolume.Text = loc.MinVolume.ToString();
            this.txtVolume.Text = loc.Volume.ToString();
            this.txtTagListeGroupId.Text = loc.TagListeGroupId.ToString();
            this.txtLocationPosition.Text = loc.LocationPosition.ToString();

            this.txtLocationRawMaterial.Text = loc.RawMaterialNumber.Trim() + " " + loc.RawMaterialName.Trim();
            this.txtLocationRawMaterial.Tag = loc.RawMaterialId;

            //Combobox: Select Group
            this.cmbLocationGroup.ValueMember = "Id";
            this.cmbLocationGroup.DisplayMember = "Name";
            this.cmbLocationGroup.DataSource = loc.LocationTypes;

            this.cmbLocationGroup.SelectedValue = Convert.ToInt32(loc.LocationTypeId);
        }

        /// <summary>
        /// Attach selected location to Raw Material by adding to list
        /// </summary>
        /// <param name="LocationId"></param>
        private void LoadLocation(Int32 LocationId)
        {
       
            RawMaterielLocation rml;
            Boolean IsLoaded = false;

            //Test if Location is already in the list
            foreach (ListViewDataItem lst in lstLocation.Items)
            {
                rml = (RawMaterielLocation)lst.Tag;
                if (rml.LocationId == LocationId)
                {
                    IsLoaded = true;
                }               
            }

            if (IsLoaded == false)
            {
                Locations loc = new Locations(true);

                foreach (Location l in loc.LocationList.Where(x => x.Id == LocationId))
                {
 
                    foreach (var lt in loc.LocationTypes.Where(x => x.Id == l.LocationTypeId))
                    {
                        rml = new RawMaterielLocation();
                        rml.IsSaved = false;
                        rml.LocationId = l.Id;
                        rml.RawMaterilaId = -1;

                        ListViewDataItem lst = new ListViewDataItem();
                        lst.Tag = rml;
                        lst.ImageKey = "silo";
                        lst.SubItems.Add("");
                        lst.SubItems.Add(lt.Name);
                        lst.SubItems.Add(l.Name);
                        lst.SubItems.Add("0"); //Quantum

                        lstLocation.Items.Add(lst);
                    }
                }
            }
            else
            {
                MessageBox.Show(MessageLocationAlraedyInList, TitleLocation, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void CalculateSum()
        {
            RawMaterials rm;
            Int64 Procent = 0; // Max = 100%
            Int64 number;
            ListViewDataItem sumLst = null;

            //Loop to recalculate SUM...
            foreach (ListViewDataItem lst in lstRecipeIngredients.Items)
            {
                rm = (RawMaterials)lst.Tag;

                if (rm.ItemType == RawMaterials.eItemType.TypeRawMaterial)
                {
                    //bool result = Int64.TryParse(lst.SubItems[3].ToString(), out number);

                    //if (result)
                    //{
                        Procent = Procent + Convert.ToInt64(lst.SubItems[3]);
                    //}
                }
            }

            //Find SUM item and update value...
            foreach (ListViewDataItem lst in lstRecipeIngredients.Items)
            {
                rm = (RawMaterials)lst.Tag;

                if (rm.ItemType == RawMaterials.eItemType.TypeSum)
                {
                    sumLst = lst;
                }
            }
            if (sumLst != null) { lstRecipeIngredients.Items.Remove(sumLst); }

            //Add calculated SUM...
            rm = new RawMaterials();
            rm.ItemType = RawMaterials.eItemType.TypeSum;
            rm.Id = -1;

            ListViewDataItem li = new ListViewDataItem();
            li.Tag = rm;
            li.BackColor = Color.LightGray;
            li.BackColor2 = Color.White;
            li.Font = new Font(this.Font, FontStyle.Bold);
            li.SubItems.Add("");
            li.SubItems.Add("");
            li.SubItems.Add("");
            li.SubItems.Add(Procent.ToString() + "%");
            li.SubItems.Add("");

            lstRecipeIngredients.Items.Add(li);
        }

        /// <summary>
        /// Test if an item is already in the listview
        /// </summary>
        /// <param name="RawMaterialId"></param>
        /// <returns></returns>
        private bool TestIfLoaded(Int32 Id)
        {

            RawMaterials rm;
            bool IsLoaded = false;

            //Test if ingridient is already in the list
            foreach (ListViewDataItem lst in lstRecipeIngredients.Items)
            {
                if (lst.Tag != null)
                {
                    if (lst.Tag is RawMaterials)
                    {
                        rm = (RawMaterials)lst.Tag;

                        if (rm.ItemType == RawMaterials.eItemType.TypeRawMaterial && rm.Id == Id)
                        {
                            IsLoaded = true;
                        }                
                    }
                }
                else
                {
                    IsLoaded = false;
                } 
            }
            return IsLoaded;
        }

        /// <summary>
        /// Loads selected rawmaterial as ingridient in a recipe
        /// </summary>
        /// <param name="RawMaterialId"></param>
        private void LoadIngredient(MenuObject o)
        {

            RawMaterials rm;
            Boolean IsLoaded = false;
            ListViewDataItem sumLst = null;

            IsLoaded = TestIfLoaded(o.Id);

            if (!IsLoaded)
            {
                //Remove Sum item...
                foreach (ListViewDataItem it in lstRecipeIngredients.Items)
                {
                    rm = (RawMaterials)it.Tag; // o.ItemObject; 
                    if (rm.ItemType == RawMaterials.eItemType.TypeSum) // = Sum item
                    {
                        sumLst = it;
                    }
                }
                if (sumLst != null) { lstRecipeIngredients.Items.Remove(sumLst); }
            }


            if (IsLoaded == false) //Item is not in the list so add it!
            {
                RawMaterials r = new RawMaterials(o.Id);
                r.RecordStatus = RawMaterials.eRecordStatus.IsAdded;

                        ListViewDataItem lst = new ListViewDataItem();
                        lst.Tag = r;
                        lst.BackColor = SetBackColor(r.BackColor);
                        lst.BackColor2 = lst.BackColor;
                        lst.Image = SetIcon("ingridient");
                        lst.SubItems.Add(""); //Icon
                        lst.SubItems.Add(r.Number.Trim());
                        lst.SubItems.Add(r.Name.Trim());
                        lst.SubItems.Add("0");
                        lst.SubItems.Add("0");
                        lst.SubItems.Add("0");
                        lst.SubItems.Add("0");

                        lstRecipeIngredients.Items.Add(lst);  
                                              
                //Add Sum item

                        rm = new RawMaterials();
                        rm.ItemType = RawMaterials.eItemType.TypeSum;
                        rm.Id = -1;

                        ListViewDataItem li = new ListViewDataItem();
                        li.Tag = rm;
                        li.BackColor = Color.LightGray;
                        li.BackColor2 = Color.White;
                        li.Font = new Font(this.Font, FontStyle.Bold);
                        li.SubItems.Add("");
                        li.SubItems.Add("");
                        li.SubItems.Add("");
                        li.SubItems.Add("0");
                        li.SubItems.Add("0");

                        lstRecipeIngredients.Items.Add(li);
            }
            else
            {
                MessageBox.Show(MessageIngridientAlreadyInList, TitleIngridient, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        /// <summary>
        /// Sets backcolor of listviewitem based on scale location (TagListeGroupId)
        /// </summary>
        /// <param name="colorstring"></param>
        /// <returns></returns>
        private Color SetBackColor(string colorstring)
        {
            Color cl = Color.White;

            try
            {
                cl = System.Drawing.ColorTranslator.FromHtml(colorstring);
            }
            catch
            {
            }
            return cl;
        }

        void lstRecipe_CellCreating(object sender, Telerik.WinControls.UI.ListViewCellElementCreatingEventArgs e)
        {
            if (e.CellElement.Data == this.lstOrderRecipeIngridients.Columns[7] && !(e.CellElement is DetailListViewHeaderCellElement))
            {
                DetailListViewVisualItem item = (DetailListViewVisualItem)
                    typeof(DetailListViewDataCellElement).GetField("row", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(e.CellElement);

                LinkCellElement lce = new LinkCellElement(item, e.CellElement.Data);
                lce.OnItemSelected += new LinkCellElement.Item_Selected(RawMaterialLocation_Selected);
                e.CellElement = lce;
            }
        }

        private bool ValidateNumeric(int KeyValue)
        {
            if (validator == null) { validator = new InputValidator(); }
            return validator.ValidateNumeric(KeyValue);
        }

        private void ValidationSetStatusMessages(OrderStatusScope StatusScope, OrderStatusType StatusType, string StatusMessageDetail = "")
        {
           
            //Test if message is already in list
            ListViewDataItem l;
            OrderStatusScope oss;
            bool IsInList = false;

            foreach (ListViewDataItem li in lstStatus.Items)
            {
                oss = (OrderStatusScope)li.Tag;
                if (StatusScope == oss)
                {
                    IsInList = true;
                }

            }

            l = new ListViewDataItem();
            l.Tag = StatusScope;

            string Message = "";

            switch (StatusType)
            {

                case OrderStatusType.TypeOK:
                    l.Image = SetIcon("ok");
                    break;

                case OrderStatusType.TypeAlert:
                    l.Image = SetIcon("alert");
                    break;

                case OrderStatusType.TypeError:
                    l.Image = SetIcon("error");
                    btnSendToProduction.Enabled = false;
                    break;

                case OrderStatusType.TypeLock:
                    l.Image = SetIcon("lock");
                    btnSendToProduction.Enabled = false;
                    break;
            }

            switch (StatusScope)
            {
                case OrderStatusScope.TypeLocationMissing:
                    Message =  MessageValidationLocationMissing;  // "Ingridient Location missing - click on 'Select Location'!";
                    break;

                case OrderStatusScope.TypeOrderContamination:
                    Message = string.Format(MessageValidationOrderContamination, StatusMessageDetail);
                     break;

                case OrderStatusScope.TypeOrderProcentDeviation:
                     Message = MessageValidationOrderProcentDeviation;
                    break;

                case OrderStatusScope.TypeOrderRunning:
                    Message = string.Format(MessageValidationOrderIsRunning, StatusMessageDetail);
                    break;

                case OrderStatusScope.TypeOrderStorageMissing:
                    Message = MessageValidationStorageLocationMissing;
                    break;

                case OrderStatusScope.TypeMinBatchSize:
                    Message = MessageValidationMinBatchSize;
                    break;

                case OrderStatusScope.TypeOrderReady:
                    Message = string.Format(MessageValidationOrderIsReady, StatusMessageDetail);
                    break;

                case OrderStatusScope.TypeOrderLocked:
                    Message = string.Format(MessageValidationOrderLocked, txtOrderNumber.Text);
                    break;
            }

           
            l.SubItems.Add("");
            l.SubItems.Add(Message);
            lstStatus.Items.Add(l);

        }

        #endregion

        #region Event Handling

        private void lstOrderRecipeIngridients_MouseDoubleClick(object sender, MouseEventArgs e)
        {

            if (lstOrderRecipeIngridients.SelectedItems.Count > 0)
            {
                RawMaterials r = (RawMaterials)lstOrderRecipeIngridients.SelectedItems[0].Tag;

                //if (r.TagListeGroupId == -1)
                //{
                this._RawMaterialId = r.Id;
                frmPickList frm = new frmPickList(r.Id, frmPickList.SelectType.TypeSingleSelect, frmPickList.ObjectType.TypeLocation);
                frm.OnItemSelected += new frmPickList.Item_Selected(RawMaterialLocation_Selected);
                frm.ShowDialog();
                //}   
            }
        }

        private void lstOrderRecipeIngridients_MouseClick(object sender, MouseEventArgs e)
        {
            if (lstOrderRecipeIngridients.SelectedItems.Count > 0)
            {
                SelectedListItem = lstOrderRecipeIngridients.SelectedItems[0];
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
           
            //TEST - command line argument to show logo or not
            try
            {
                String x = Environment.GetCommandLineArgs()[1];
                if (x == "nologo")
                {
                    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                    picLogo.Visible = false;
                }
            }
            catch
            {
            }

            pvMainContent.Pages.Clear();
            pvRightPane.Pages.Clear();

            pvMainContent.Controls.Add(pvpOrderList);
            pvMainContent.SelectedPage = pvpOrderList;
            pvRightPane.Controls.Add(pvpInfoBoard);

            OrderOrderList();

            this.timer1.Interval = 10000; //10 sec.
            this.timer1.Start();
            LoadLiveBatchData();

            lstLocation.ImageList = this.ImageList.Img16x16;
            lstRawMaterial.ImageList = this.ImageList.Img16x16;
   
        }

        /// <summary>
        /// Test method - Toggles between english and korean language
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblLanguage_Click(object sender, EventArgs e)
        {
            if (lblLanguage.Tag != null)
            {
                if (lblLanguage.Tag.ToString() == "en_US")
                {
                    lblLanguage.Tag = "ko_KR";
                    lblLanguage.Text = "Language: KR";
                    this.UIlang = "ko_KR";
                    LoadSystem();
                    ChangeControlsUI("ko_KR");
                }
                else
                {
                    lblLanguage.Tag = "en_US";
                    lblLanguage.Text = "Language: EN";
                    this.UIlang = "en_US";
                    LoadSystem();
                    ChangeControlsUI("en_US");
                }

            }
            else
            {
                lblLanguage.Tag = "ko_KR";
                this.UIlang = "ko_KR";
                lblLanguage.Text = "Language: KR";
                LoadSystem();
                ChangeControlsUI("ko_KR");
            }
        }

        private void MenuTree_DragEnding(object sender, Telerik.WinControls.UI.RadTreeViewDragCancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void MenuTree_ItemDrag(object sender, RadTreeViewEventArgs e)
        {
            DragNode = e.Node;
            //DoDragDrop(e.Node, DragDropEffects.Copy);
        }

        private void MenuTree_DragDrop(object sender, DragEventArgs e)
        {
            
        }

        private void DragDropService_PreviewDragDrop(object sender, Telerik.WinControls.RadDropEventArgs e)
        {

            //Detect where user i trying to drop item.
            //If drop is not in correct order the drop must be cancelled
            //1. Hold a cached list of TagListeGroupId
            //2. Find TagListeGroupId listitem on drop location to get its TagListeGroupId
            //3. Find TagListeGroupId og dragged item
            //4. If dragged item has taglistegroupid > dropped item the drop must be cancelled
            //5. I

            //var lst = e.DragInstance as ListViewDataItem;

            //lst.BackColor = Color.Red;
           
            if (e.DropLocation.X > 200)
            {
                e.Handled = true;
            }
        }

        private void btnValidateOrder_Click(object sender, EventArgs e)
        {

            lstStatus.Items.Clear();
            ValidationMessagesCount = 0;

            if (lstOrderStorage.Items.Count == 0)
            { 
                ValidationSetStatusMessages(OrderStatusScope.TypeOrderStorageMissing, OrderStatusType.TypeError);
                ValidationMessagesCount += 1;
            }

                this.timer1.Stop();
                Int64 Quantum = Convert.ToInt64(txtOrderQuantum.Text);
                Int64 BatchSize = Convert.ToInt64(this.txtRecBatchSize.Text);

                Recipe rcp = (Recipe)btnValidateOrder.Tag;

                this._RecipeId = rcp.Id;
                ListIngridients = rcp.RawMaterialList;
                LoadOrderIngredientList(Quantum);
      
                ValidateOrder(this.txtOrderNumber.Text.Trim(), Quantum, BatchSize);
                
                if (ValidationMessagesCount == 0)
                {
                    ValidationSetStatusMessages(OrderStatusScope.TypeOrderReady, OrderStatusType.TypeOK, pvpOrder.Text);
                    btnSendToProduction.Enabled = true;
                }
                else
                {
                    MessageBox.Show(MessageOrderValidation, TitleOrderValidation, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }

        }

        /// <summary>
        /// Finds the correct action depending on the menu clicked...
        /// </summary>
        /// 
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuTree_DoubleClick(Object sender, EventArgs e)
        { 
            Telerik.WinControls.UI.RadTreeView tmpView = (Telerik.WinControls.UI.RadTreeView)sender;
            if (tmpView.SelectedNode != null)
            {


            if (tmpView.SelectedNode.Tag != null)
            {
                MenuObject o = (MenuObject)tmpView.SelectedNode.Tag;

                switch (o.MenuType)
                {
                    case MenuObject.eMenuType.TypeMenu:

                    SelectedMenu = (MenuAction)o.Id; //Cast Menu Id as enum: MenuAction

                    switch (SelectedMenu) //Menu_Id
                    {
                        case MenuAction.OrderHandlingNewOrder:
                            OrderHandlingNewOrder();
                            break;

                        case MenuAction.RawMaterialAddNew:
                            RawMaterialAddNew();
                            break;

                        case MenuAction.RawMaterialList:
                            RawMaterialList();
                            break;

                        case MenuAction.RawMaterialLocation:
                            break;

                        case MenuAction.RecipeAddNew:
                            RecipeAddNew();
                            break;

                        case MenuAction.OrderOrderList:
                            OrderOrderList();
                            break;

                        case MenuAction.LocationLocationGroups:
                            LoadLocationList();
                            break;

                        case MenuAction.RecipeList:
                            LoadRecipeList();
                            break;

                        default:
                            MessageBox.Show(tmpView.SelectedNode.Text + ": " + o.Id.ToString());
                            break;

                    }
                        break;

                    case MenuObject.eMenuType.TypeLocation:

                        switch (o.MenuContext)
                        {
                            case MenuObject.MainMenu.MenuLocation:
                                LoadLocationEdit(o.Id);
                                break;

                            case MenuObject.MainMenu.MenuRawMaterial:
                                 LoadLocation(o.Id); //Loads selected Location to relation list for selected rawmaterial
                                break;
                        }
                        break;

                    case MenuObject.eMenuType.TypeRawMaterial:

                        switch (o.MenuContext)
                        {
                            case MenuObject.MainMenu.MenuRawMaterial:
                                LoadRawMaterial(o.Id);
                                break;

                            case MenuObject.MainMenu.MenuRecipe:
                                LoadIngredient(o);
                                break;
                        }                     
                        break;

                    case MenuObject.eMenuType.TypeRecipe:
                        LoadRecipe(o.Id);
                        break;

                    case MenuObject.eMenuType.TypeOrder:
                        LoadOrder(o.Id);
                        break;

                    case MenuObject.eMenuType.TypeReport:
                        
                        ShowReport(o);
                        break;

                }
            }
            }
        }

        private void btnAddLocation_Click(object sender, EventArgs e)
        {
            frmPickList frm = new frmPickList(0, frmPickList.SelectType.TypeSingleSelect, frmPickList.ObjectType.TypeLocation);
            frm.ShowDialog();
        }

        private void lstLocation_DragDrop(object sender, DragEventArgs e)
        {
            MessageBox.Show(sender.ToString());
        }

        private void lstLocation_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        private void lstLocation_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(RadTreeView)))
            {
                e.Effect = DragDropEffects.Move;
            }
        }

        private void RadProgressBar_Click(object sender, EventArgs e)
        {

           RadProgressBar pgb = (RadProgressBar)sender;

           int OrderId = Convert.ToInt32(pgb.Tag);
           LoadOrder(OrderId);
        }

        private void btnSaveRawMaterial_Click(object sender, EventArgs e)
        {
            //Edit existing or submit new
            RawMaterielLocation rml;

            if (txtRawMaterialName.Text != "" && txtRawMaterialNumber.Text != "" )
            {
                    RawMaterials raw = new RawMaterials();

                    if (_SaveAction == SaveAction.TypeEdit)
                    {
                        raw.ActionType = RawMaterials.eActionType.TypeEdit; //Flag for edit existing
                        raw.Id = this._ObjectID;
                    }
                    else if (_SaveAction == SaveAction.TypeNew)
                    {
                        raw.ActionType = RawMaterials.eActionType.TypeNew; //Flag for submit new 
                    }

                    raw.Density = this.txtRawMaterialDensity.Text;
                    raw.Name = this.txtRawMaterialName.Text; ;
                    raw.Number = this.txtRawMaterialNumber.Text;
                    raw.GroupId = Convert.ToInt64(this.cmbRawMaterialGroup.SelectedValue); //Each raw material is a part of a group: like "Vitamins", "Proteins", etc
                  
                    List<RawMaterielLocation> col = new List<RawMaterielLocation>();

                    //Loop each assigned locations and add to collection
                    foreach (ListViewDataItem lst in lstLocation.Items)
                    {
                        rml = (RawMaterielLocation)lst.Tag;
                        col.Add(rml);                      
                    }

                    raw.RawMaterialLocationCollection = col;
                    raw.Save();

                    RawMaterialIsLoaded = false;
                    RawMaterialList();

            }
            else
            {
                MessageBox.Show(MessageRawImaterialNameOrNumberMissing, TitleRawImaterialNameOrNumberMissing, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

        private void lstRawMaterial_DoubleClick(object sender, EventArgs e)
        {

            if (lstRawMaterial.SelectedItem != null)
            {
                Int32 RawMaterialId = Convert.ToInt32(lstRawMaterial.SelectedItem.Tag);
                LoadRawMaterial(RawMaterialId);
            }
        }

        private void btnSaveRecipe_Click(object sender, EventArgs e)
        {

            //Edit existing or submit new
            RawMaterials rm;

            if (this.txtRecipeName.Text != "" && this.txtRecipeNumber.Text != "")
            {
                if (this.lstRecipeIngredients.Items.Count > 0)
                {
                    Recipe r = new Recipe();

                    if (_SaveAction == SaveAction.TypeEdit)
                    {
                        r.ActionType = Recipe.eActionType.TypeEdit; //Flag for edit existing
                        r.Id = this._ObjectID;
                    }
                    else if (_SaveAction == SaveAction.TypeNew)
                    {
                        r.ActionType = Recipe.eActionType.TypeNew; //Flag for submit new 
                    }

                    r.RecipeName = this.txtRecipeName.Text;
                    r.RecipeNumber = this.txtRecipeNumber.Text;
                    r.DefaultOrderQuantum = Convert.ToInt32(this.txtDefaultQuantum.Text);
                    r.MinBatchSize = Convert.ToInt32(this.txtRecipeMinBatch.Text);
                    r.RecBatchSize = Convert.ToInt32(this.txtRecipeRecBatchSize.Text);
                    r.EndProductName = txtRecipeEndProductName.Text;
                    r.Note = this.txtRecipeNote.Text;

                    List<APC.RawMaterials> col = new List<APC.RawMaterials>();

                    //Loop each assigned raw material and add to collection
                    foreach (ListViewDataItem lst in lstRecipeIngredients.Items)
                    {
                        rm = (APC.RawMaterials)lst.Tag;

                        if (rm.ItemType != RawMaterials.eItemType.TypeSum && lst.SubItems[3] != null)
                        {
                            rm.AmountProcent = Convert.ToInt64(lst[3]);
                            col.Add(rm);
                        }
                    }
                    r.RawMaterialList = col;
                    r.Save();

                    //LoadSystem(); //Reload tree menu  TODO: only reload part of menu 
                }
                else
                {
                    MessageBox.Show(MessageIngridientMissing, TitleIngridient, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

            }
            else
            {
                MessageBox.Show(MessageRecipeNameOrNumberMissing, TitleRecipe, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void lstRecipeIngredients_ItemRemoving(object sender, ListViewItemCancelEventArgs e)
        {
            if (MessageBox.Show(MessageIngridientRemove, TitleIngridient, MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.OK)
            {
                e.Cancel = false;

                RawMaterials rm;
                Recipe r;
                ListViewDataItem lst = (ListViewDataItem)e.Item;

                rm = (RawMaterials)lst.Tag;

                foreach (RawMaterials rw in this.ListIngridients)
                {
                    if (rw.Id == rm.Id)
                    {
                        if (rw.RecordStatus == RawMaterials.eRecordStatus.IsNotChanged)
                        {
                            rw.RecordStatus = RawMaterials.eRecordStatus.IsDeleted;
                        }
                    }

                }
                //r = new Recipe();
                //r.RawMaterialId = rm.Id;
                //r.Id = rm.RecipeId;
                //r.ActionType = Recipe.eActionType.TypeDeleteRawMaterial;
                //r.Save();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void btnSendToProduction_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;

            switch (this._SaveAction)
            {
                case SaveAction.TypeEdit:
                    if (MessageBox.Show(MessageSendToProduction, TitleOrder, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                    {
                        //Make list of storage locations
                        List<APC.Common.Location> lstStorage = new List<APC.Common.Location>();
                        foreach (RadListDataItem i in lstOrderStorage.Items)
                        {
                            lstStorage.Add((APC.Common.Location)i.Tag);
                        }

                        Order o = new Order();

                        o.Id = this._OrderId;
                        o.StorageLocationList = lstStorage;
                        o.ActionType = Order.eActionType.TypeEdit;
                        o.OrderNumber = txtOrderNumber.Text;
                        o.OrderQuantum = Convert.ToInt32(txtOrderQuantum.Text);
                        o.RecipeId = this._RecipeId;
                        o.OrderStatus = 0;
                        o.Name = txtEndProductName.Text;
                        o.RecommendedBatchSize = Convert.ToInt32(txtRecBatchSize.Text);
                        o.Save();

                        //Delete all tags from BatchList on this orderid before sending new values
                        Batch b = new Batch();
                        b.OrderId = this._OrderId;
                        b.RemoveOrderFromBatchListe();

                        //Send re-calculated tags to BatchList
                        SendToBatchListe();
                        o.SetOrderState(Order.OrderState.ReadyForProduction); //Unlock the Order for Bridge/Zenon

                        lnkRunningOrderStatus_LinkClicked(null, null);
                    }

                    break;

                case SaveAction.TypeNew:
                    if (MessageBox.Show(MessageSendToProduction, TitleOrder, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                    {
                        //Send list of storage locations
                        List<APC.Common.Location> lstStorage = new List<APC.Common.Location>();
                        foreach (RadListDataItem i in lstOrderStorage.Items)
                        {
                            lstStorage.Add((APC.Common.Location)i.Tag);
                        }

                        Order o = new Order();

                        o.SaveOrderPostfixNumber(this._OrderPostfixNumber);
                        o.StorageLocationList = lstStorage;
                        o.IngredientList = ListIngridients;
                        o.ActionType = Order.eActionType.TypeSave; //Flag for submit new 
                        o.OrderNumber = txtOrderNumber.Text;
                        o.OrderQuantum = Convert.ToInt32(txtOrderQuantum.Text);
                        o.RecipeId = this._RecipeId;
                        o.OrderStatus = 0;
                        o.Name = txtEndProductName.Text;
                        o.RecommendedBatchSize = Convert.ToInt32(txtRecBatchSize.Text);
                        o.Save();

                        this._OrderId = o.Id; //Return id of newly created order
                        this._OrderSequence = o.OrderSequence; //returns newly calculated order sequence = the sort order in quoue

                        SendToBatchListe();
                        o.SetOrderState(Order.OrderState.ReadyForProduction); //Unlock the Order for Bridge/Zenon
                        lnkRunningOrderStatus_LinkClicked(null, null);
  
                    }
                    break;
            }

            System.Windows.Forms.Cursor.Current = Cursors.Default;
        }

        /// Grabs the actual running orders batchlist and shows status in grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lnkRunningOrderStatus_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
 
            if (pvMainContent.SelectedPage != pvpOrderList)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpOrderList);
            }
 
            LoadLiveBatchData();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            LoadLiveBatchData();
        }

        private void lstRecipeIngredients_ItemValueChanged(object sender, ListViewItemValueChangedEventArgs e)
        {
            Decimal ProcentSum = 0;
            RawMaterials rm;
            ListViewDataItem lstSum = null;

            //Set status of changed ingridient: IsEdited
            ListViewDataItem l = (ListViewDataItem)e.Item;
            RawMaterials r = (RawMaterials)l.Tag;

            if (r.RecordStatus != RawMaterials.eRecordStatus.IsAdded) //Since ingridient is added this flags overrules IsEdited
            {
                r.RecordStatus = RawMaterials.eRecordStatus.IsEdited;
            }


            //Loop all rawmaterials and calculate sum in procent
            foreach (ListViewDataItem lst in lstRecipeIngredients.Items)
            {
                rm = (RawMaterials)lst.Tag;

                if (rm.ItemType == RawMaterials.eItemType.TypeSum)
                {
                    lstSum = lst;
                }
                else
                {
                    ProcentSum += Convert.ToDecimal(lst[3]);
                }
            }

            if (lstSum != null)
            {
                lstSum[3] = ProcentSum.ToString() + "%";
                if (ProcentSum > 100 || ProcentSum < 100)
                {
                    lstSum.BackColor = Color.Red;
                    lstSum.BackColor2 = Color.White;
                }
                else
                {
                    lstSum.BackColor = Color.LightGray;
                    lstSum.BackColor2 = Color.White;
                }

            }


        }

        private void lstRecipeIngredients_ItemMouseDown(object sender, ListViewItemMouseEventArgs e)
        {

            RawMaterials rm = (RawMaterials)e.Item.Tag;

            this.lstRecipeIngredients.AllowDragDrop = true;

            if (rm.ItemType == RawMaterials.eItemType.TypeSum) //The SUM item in list can not be dragged
            {
                this.lstRecipeIngredients.AllowDragDrop = false;
            }
            else
            {
                //DoDragDrop(e.Item, DragDropEffects.Move);
            }
        }

        private void lstRecipeIngredients_DragDrop(object sender, DragEventArgs e)
        {
            IDataObject dataObject = e.Data;

            if (dataObject != null)
            {

                Telerik.WinControls.UI.RadTreeNode Node = dataObject.GetData(typeof(Telerik.WinControls.UI.RadTreeNode)) as Telerik.WinControls.UI.RadTreeNode;

                if (Node != null)
                {

                    //Check if ingridiens is already in list
                    //Insert new listdataitem
                }

            }
        }

        private void lstRecipeIngredients_DragOver(object sender, DragEventArgs e)
        {
            MessageBox.Show("dropped!");
        }

        private void btnMakeOrder_Click(object sender, EventArgs e)
        {
            pvMainContent.Pages.Clear();
            pvMainContent.Pages.Add(pvpOrder);

            Recipe rcp = new Recipe(this._RecipeId);
            Order o = new Order();

            this.txtOrderNumber.Text = o.GetNextOrderNumber();
            this._OrderPostfixNumber = o.OrderPostfixNumber;
            
            pvpOrder.Text = "New Order: " + this.txtOrderNumber.Text;

            this._SaveAction = SaveAction.TypeNew;

            lstOrderStorage.Items.Clear();
            btnAddStorageLocation.Enabled = true;
            btnValidateOrder.Enabled = true;
            btnRemoveStorageLocation.Enabled = false;

            this.txtRecipeName.Text = rcp.RecipeName;
            this.txtRecipeNumber.Text = rcp.RecipeNumber;
            this.txtRecipeEndProductName.Text = rcp.EndProductName;
            this.txtOrderQuantum.Text = rcp.DefaultOrderQuantum.ToString();
            this.txtOrderNumber.Text = o.GetNextOrderNumber();
            this.txtOrderMinBatchSize.Text = rcp.MinBatchSize.ToString();
            this.txtRecipeRecBatchSize.Text = rcp.RecBatchSize.ToString();
            this.txtRecipeMinBatch.Text = rcp.MinBatchSize.ToString();
            this.txtRecipeNote.Text = rcp.Note;

            this.btnValidateOrder.Tag = rcp; //Use this recipe object in btnCalculateBatches_Click if user later changes values of quantum 
            this.txtRecipe.Text = rcp.RecipeName;
            this.txtRecipe.Tag = this._RecipeId;
            this.txtRecBatchSize.Text = rcp.RecBatchSize.ToString();
            this.txtRecBatchSize.Tag = rcp.RecBatchSize.ToString(); //Remembers value, to later determine if user has changed this
            this.txtEndProductName.Text = rcp.EndProductName;

            ListIngridients = rcp.RawMaterialList;
            LoadOrderIngredientList();

        }

        private void btnSaveLocation_Click(object sender, EventArgs e)
        {
            APC.Common.RawMaterial r = (APC.Common.RawMaterial)txtLocationRawMaterial.Tag;

            Locations l = new Locations();
            l.LocationId = _LocationId;
            l.Description = "";
            l.LocationName = txtLocationName.Text;
            l.MaxVolume = Convert.ToInt32(txtMaxVolume.Text);
            l.MinVolume = Convert.ToInt32(txtMinVolume.Text);
            l.Volume = Convert.ToInt32(txtVolume.Text);
            l.TagListeGroupId = Convert.ToInt32(txtTagListeGroupId.Text);
            l.LocationPosition = Convert.ToInt32(txtLocationPosition.Text);
            l.RawMaterialId = r.Id;
            l.RawMateralChanged = RawMaterialChanged;
            l.Save();

            //Reset flag
            RawMaterialChanged = false;
        }

        private void lstRecipeIngredients_DragEnter(object sender, DragEventArgs e)
        {

            MessageBox.Show("test!");
        }

        private void btnBrowseRawMaterial_Click(object sender, EventArgs e)
        {

            frmPickList frm = new frmPickList(this._RawMaterialId, frmPickList.SelectType.TypeSingleSelect, frmPickList.ObjectType.TypeRawMaterial);
            frm.OnItemSelected += new frmPickList.Item_Selected(RawMaterial_Selected);
            frm.ShowDialog();

        }

        private void radButton2_Click(object sender, EventArgs e)
        {

            frmPickList frm = new frmPickList(this._RawMaterialId, frmPickList.SelectType.TypeSingleSelect, frmPickList.ObjectType.TypeRawMaterial);
 


            //frm.RawMaterial_Selected += new EventHandler(RawMaterial_Selected);

            frm.ShowDialog();
        }

        private void RawMaterial_Selected(object sender, EventArgs e)
        {
            APC.Common.RawMaterial rm = (APC.Common.RawMaterial)sender;
           
                if (txtLocationRawMaterial.Tag != sender) //User has changed raw material for selected location
                {
                    RawMaterialChanged = true; //This flag is read when saving properties for selected location
                }
           
            txtLocationRawMaterial.Text = rm.MaterialNumber.Trim() + " " + rm.Name.Trim();
            txtLocationRawMaterial.Tag = sender;   
        }

        private void RawMaterialNegative_Selected(object sender, EventArgs e)
        {
            APC.Common.RawMaterial r = (APC.Common.RawMaterial)sender;
            APC.RawMaterials raw;
            
            bool IsInList = false;

            foreach (ListViewDataItem lst in lstRecipeNegativeList.Items)
            {
                raw = (APC.RawMaterials)lst.Tag;

                if (raw.Id == r.Id)
                {
                    IsInList = true;
                }
            }

            if (IsInList)
            {
                MessageBox.Show(MessageIngridientAlreadyInList, TitleIngridient, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                RawMaterials rw = new RawMaterials(r.Id);
                
                rw.RecordStatus = RawMaterials.eRecordStatus.IsAdded;
                rw.RecipeId = _RecipeId;
                ListNegativeRawMaterials.Add(rw); //Add new to cache list, for later saving

                ListViewDataItem li = new ListViewDataItem();
                li.Tag = rw;
                li.Image = SetIcon("ingridient");
                li.SubItems.Add("");
                li.SubItems.Add(r.MaterialNumber);
                li.SubItems.Add(r.Name);
                li.SubItems.Add("0");

                lstRecipeNegativeList.Items.Add(li);
            }
        }

        private void RawMaterialForRecipe_Selected(object sender, EventArgs e)
        {
            bool IsInList = false;
            APC.Common.RawMaterial r = (APC.Common.RawMaterial)sender;

            RawMaterials raw;
            foreach (ListViewDataItem l in lstRecipeIngredients.Items)
            {
                raw = (RawMaterials)l.Tag;
                if (raw.Id == r.Id)
                {
                    IsInList = true;
                }
            }


            if (!IsInList)
            {

                RawMaterials rw = new RawMaterials(r.Id);
                rw.RecordStatus = RawMaterials.eRecordStatus.IsAdded;

                if (rw.RawMaterialLocations != null)
                {
                    if (rw.RawMaterialLocations.Count == 1)
                    {
                        rw.TagListeGroupId = Convert.ToInt32(rw.RawMaterialLocations[0].TagListeGroupId);
                        rw.LocationName = rw.RawMaterialLocations[0].Name;
                        rw.ColorMap = rw.RawMaterialLocations[0].ColorMap;
                    }

                }

                ListIngridients.Add(rw);
                ListIngridients = ListIngridients.OrderBy(x => x.TagListeGroupId).ToList();

                LoadRecipeIngredientList();
            }
            else
            {
                MessageBox.Show(MessageIngridientAlreadyInList, TitleIngridient, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

      
 
            //MenuObject o = new MenuObject();
            //o.Id = Convert.ToInt32(r.Id);
            //LoadIngredient(o);
      
        }

        /// <summary>
        /// Late binding: User has selected a location for rawmaterial - reload list to sort and color background
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RawMaterialLocation_Selected(object sender, EventArgs e)
        {
            APC.Common.Location l = (APC.Common.Location)sender;
            APC.Locations loc = new APC.Locations(l.Id);

            APC.RawMaterials rm = new APC.RawMaterials(_RawMaterialId);


            //Reload ingridients list and sort by TagListGroupId + color background
            foreach (RawMaterials raw in ListIngridients)
            {
                if (raw.Id == _RawMaterialId)
                {
                    raw.TagListeGroupId = Convert.ToInt32(loc.TagListeGroupId);
                    raw.LocationName = loc.LocationName;
                    raw.LocationId = l.Id;
                    raw.ColorMap = loc.ColorMap;
                
                }
            }
           
            //Reload list to sort + color background
            int Quantum = Convert.ToInt16(txtOrderQuantum.Text);
            LoadOrderIngredientList(Quantum);
        }

        private void Location_Selected(object sender, EventArgs e)
        {
            APC.Common.Location loc = (APC.Common.Location)sender;
            
            RawMaterielLocation rm = new RawMaterielLocation();
            rm.LocationId = loc.Id;
            rm.RawMaterilaId = _RawMaterialId;
            rm.IsSaved = false;

            ListViewDataItem l = new ListViewDataItem();
            l.Tag = rm;
            l.Image = SetIcon("silo");
            l.SubItems.Add("");
            l.SubItems.Add(loc.Name);
            l.SubItems.Add(loc.Name);

            lstLocation.Items.Add(l);
        }

        private void StorageLocation_Selected(object sender, EventArgs e)
        {
            APC.Common.Location l = (APC.Common.Location)sender;
            bool IsAddedBefore = false;

            if (lstOrderStorage.Items.Count > 0)
            { 
                //Test if storage location is already selected
                foreach (RadListDataItem rld in lstOrderStorage.Items)
                {
                    APC.Common.Location loc = (APC.Common.Location)rld.Tag;

                    if (loc.Id == l.Id)
                    {
                        IsAddedBefore = true;
                    }
                }

            }

            if (!IsAddedBefore)
            {
                RadListDataItem ri = new RadListDataItem();
                ri.Text = l.Name;
                ri.Tag = l;
                lstOrderStorage.Items.Add(ri);

                if (lstOrderStorage.Height != 80) //Show max 4 entries
                {
                    lstOrderStorage.Height = lstOrderStorage.Items.Count * 20;
                }

                btnValidateOrder.Enabled = true;
                btnRemoveStorageLocation.Enabled = true;
            }
            else
            {
                MessageBox.Show(MessageLocationAlraedyInList, TitleLocation, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }    
        }

        /// <summary>
        /// Selected Recipe for order
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Recipe_Selected(object sender, EventArgs e)
        {
            Common.Recipe r = (Common.Recipe)sender;

            txtRecipe.Text = r.RecipeNumber.Trim() + " " + r.RecipeName.Trim();
            txtRecipe.Tag = r;

            _RecipeId = r.Id;
            rcp = new Recipe(r.Id);
          
            btnValidateOrder.Enabled = true;
            btnValidateOrder.Tag = rcp;

            this.txtRecBatchSize.Text = rcp.RecBatchSize.ToString();
            this.txtEndProductName.Text = rcp.EndProductName;
            this.txtOrderQuantum.Text = rcp.DefaultOrderQuantum.ToString();
            this.txtOrderMinBatchSize.Text = rcp.MinBatchSize.ToString();

            ListIngridients = rcp.RawMaterialList;
            LoadOrderIngredientList(); //Loads list of ingridients for selected Recip
        }

        private void btnRemoveNegativeRawMatrerial_Click(object sender, EventArgs e)
        {
            List<ListViewDataItem> RemoveIndex = new List<ListViewDataItem>();

            foreach (ListViewDataItem lst in lstRecipeNegativeList.SelectedItems)
            {
                RemoveIndex.Add(lst);
            }

            foreach (ListViewDataItem lst in RemoveIndex)
            {
                lstRecipeNegativeList.Items.Remove(lst);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {


            
            //System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
            //System.Data.SqlClient.SqlCommand cmd;
            //System.Data.SqlClient.SqlDataReader rdr = null;


            //conn.ConnectionString = "data source=192.168.0.192;user id=sa;password=Weekend1519;persist security info=False;database=Andritz_APC";
            //try
            //{
            //    conn.Open();

            //    string CommandText = "SELECT * " +
            //                        "FROM BatchListe " +
            //                        "WHERE BatchCountNo > 3 ";
            //    cmd = new System.Data.SqlClient.SqlCommand(CommandText);
            //    cmd.Connection = conn;

            //    rdr = cmd.ExecuteReader();

            //    MessageBox.Show(conn.State.ToString());

            //    conn.Close();

            //    MessageBox.Show(conn.State.ToString());

            //}
            //catch (System.Data.SqlClient.SqlException ex)
            //{
            //    MessageBox.Show(ex.Message, ex.Number.ToString());
            //}

        }

        private void radButton1_Click(object sender, EventArgs e)
        {

            if (lstActiveOrderList.SelectedItems.Count > 0)
            {

                int OrderId = 0;
                ListViewDataItem lst = lstActiveOrderList.SelectedItems[0];

                OrderId = (int)lst.Tag;


                if (lst[9].ToString() == "in process")
                {
                    MessageBox.Show(MessageOrderIsLocked, TitleOrder, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    if (MessageBox.Show(string.Format(MessageRemoveOrder, ""), TitleOrder, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                    {
                        Order o = new Order();
                        o.Id = OrderId;
                        o.Delete();

                        Batch b = new Batch();
                        b.OrderId = OrderId;
                        b.RemoveOrderFromBatchListe();

                        //Remove all items from batchliste whith selected order id
                        //Delete order form table: Order
                        lstActiveOrderList.Items.Remove(lst);
                    }
                }

            }
        }

        private void lnkUpdateOrderSequence_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Batch b = new Batch();

            b.UpdateOrderSequence();
        }

        private void btnAddOrder_Click(object sender, EventArgs e)
        {
            OrderHandlingNewOrder();
        }

        /// <summary>
        /// Edit or view a order. If order is in progress it can not be edited!
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstActiveOrderList_DoubleClick(object sender, EventArgs e)
        {
            if (lstActiveOrderList.SelectedItems.Count > 0)
            {
                int OrderId = 0;
                ListViewDataItem lst = lstActiveOrderList.SelectedItems[0];
                OrderId = (int)lst.Tag;
                LoadOrder(OrderId);
            }
        }

        private void btnOrderSequenceUp_Click(object sender, EventArgs e)
        {

            try
            {
                //if (lstActiveOrderList.SelectedIndex > 0)
                //{

                //    int index = lstActiveOrderList.SelectedIndex;
                //    ListViewDataItem current = lstActiveOrderList.SelectedItem as ListViewDataItem;
                //    lstActiveOrderList.Items.Remove(current);
                //    lstActiveOrderList.Items.Insert(index - 1, current);
                //    lstActiveOrderList.SelectedIndex = index - 1;

                //}
            }
            catch (Exception ex)
            {
            }


        }

        private void btnOrderSequenceDown_Click(object sender, EventArgs e)
        {
            try
            {
                //if ((lstActiveOrderList.SelectedIndex > -1) && (lstActiveOrderList.SelectedIndex < lstActiveOrderList.Items.Count - 1))
                //{
                //    int index = lstActiveOrderList.SelectedIndex;
                //    ListViewDataItem current = lstActiveOrderList.SelectedItem as ListViewDataItem;
                //    lstActiveOrderList.Items.Remove(current);
                //    lstActiveOrderList.Items.Insert(index + 1, current);
                //    lstActiveOrderList.SelectedIndex = index + 1;
                //}
            }
            catch (Exception ex)
            {
            }


        }

        private void lstLocationList_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (lstLocationList.SelectedItems.Count > 0)
                {
                    int LocationId = 0;
                    ListViewDataItem lst = lstLocationList.SelectedItems[0];
                    LocationId = (int)lst.Tag;
                    LoadLocationEdit(LocationId);
                }
            }
            catch
            {
            }
        }

        private void lnkLocationList_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            LoadLocationList();
        }

        private void btnAddRawMaterial_Click(object sender, EventArgs e)
        {
            RawMaterialAddNew();
        }

        private void btnDeleteRawMaterial_Click(object sender, EventArgs e)
        {
            if (lstRawMaterial.SelectedItems.Count > 0)
            {
                if (MessageBox.Show(MessageRawMaterialDelete, TitleRawMaterial, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                {
                    int Id = 0;
                    ListViewDataItem lst = lstRawMaterial.SelectedItems[0];
                    Id = (int)lst.Tag;

                    RawMaterials r = new RawMaterials();
                    r.Id = Id;
                    r.ActionType = RawMaterials.eActionType.TypeDelete;
                    r.Save();

                    RawMaterialIsLoaded = false;
                    LoadRawMaterialList();
                }
            }
        }

        /// <summary>
        /// Test Method
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lnkResetVolume_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            Locations l = new Locations();

            l.SetVolumneToMaxVolume();
        }

        /// <summary>
        /// Test Method
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lnkSetVolumeNegative_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            if (lstLocationList.SelectedItems.Count > 0)
            {
                Locations l = new Locations();

                int LocationId = 0;
                ListViewDataItem lst = lstLocationList.SelectedItems[0];
                LocationId = (int)lst.Tag;

                l.SetVolumeNegative(LocationId);
            }
        }

        private void lnkResetVolume_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (lstLocationList.SelectedItems.Count > 0)
            {
                Locations l = new Locations();

                int LocationId = 0;
                ListViewDataItem lst = lstLocationList.SelectedItems[0];
                LocationId = (int)lst.Tag;

                l.SetVolumeReset(LocationId);
            }
        }

        private void lnkResetBatches_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Order o = new Order();
            o.ResetStatusBatches();
        }

        private void lnkDeleteOrdersBatches_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Order o = new Order();
            o.DeleteOrdersBatches();
        }

        private void lnkMarkOrderFinished_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (lstActiveOrderList.SelectedItems.Count > 0)
            {
                int OrderId = 0;
                ListViewDataItem lst = lstActiveOrderList.SelectedItems[0];
                OrderId = (int)lst.Tag;
                Order o = new Order();
                o.MarkOrderFinished(OrderId);

            }
        }

        private void btnSaveRecipe2_Click(object sender, EventArgs e)
        {
            //Edit existing or submit new
            RawMaterials rm;

            if (this.txtRecipeName.Text == "")
            {
                MessageBox.Show(MessageRecipeNameMissing, TitleRecipe, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (this.txtRecipeNumber.Text == "")
            {
                MessageBox.Show(MessageRecipeNumberMissing, TitleRecipe, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (this.txtRecipeEndProductName.Text == "")
            {
                MessageBox.Show(MessageRecipeEndProductNameMissing, TitleRecipe, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (this.txtDefaultQuantum.Text == "" || this.txtDefaultQuantum.Text == "0")
            {
                MessageBox.Show(MessageRecipeDefaultQuantityMissing, TitleRecipe, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (this.txtRecipeRecBatchSize.Text == "" || this.txtRecipeRecBatchSize.Text == "0")
            {
                MessageBox.Show(MessageRecipeRecBatchSizeMissing, TitleRecipe, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (this.txtRecipeMinBatch.Text == "" || this.txtRecipeMinBatch.Text == "0")
            {
                MessageBox.Show(MessageRecipeMinBatchSizeMissing, TitleRecipe, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            bool AmountProcentMissing = false;
           
            Decimal AmountProcentTotal = 0;
            Decimal AmountProcent = 0;

            foreach (RawMaterials raw in ListIngridients)
            {
                    AmountProcent = raw.AmountProcent;
                    AmountProcentTotal += AmountProcent;

                    if (AmountProcent == 0)
                    {
                        AmountProcentMissing = true;
                    }
            }
            if (AmountProcentMissing)
            {
                MessageBox.Show(MessageRecipeIngridientAmountProcentMissing, TitleRecipe, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else if (AmountProcentTotal < 100 || AmountProcentTotal > 100)
            {
                MessageBox.Show(MessageRecipeTotalAmountNot100Procent, TitleRecipe, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }


                if (this.lstRecipeIngredients.Items.Count > 0)
                {
                    Recipe r = new Recipe();

                    if (_SaveAction == SaveAction.TypeEdit)
                    {
                        r.ActionType = Recipe.eActionType.TypeEdit; //Flag for edit existing
                        r.Id = this._RecipeId;
                    }
                    else if (_SaveAction == SaveAction.TypeNew)
                    {
                        r.ActionType = Recipe.eActionType.TypeNew; //Flag for submit new 
                    }

                    r.RecipeName = this.txtRecipeName.Text;
                    r.RecipeNumber = this.txtRecipeNumber.Text;
                    r.DefaultOrderQuantum = Convert.ToInt32(this.txtDefaultQuantum.Text);
                    r.MinBatchSize = Convert.ToInt32(this.txtRecipeMinBatch.Text);
                    r.RecBatchSize = Convert.ToInt32(this.txtRecipeRecBatchSize.Text);
                    r.EndProductName = txtRecipeEndProductName.Text;
                    r.Note = this.txtRecipeNote.Text;
                    r.RawMaterialNegativeList = ListNegativeRawMaterials; // colNegative;

                    List<APC.RawMaterials> col = new List<APC.RawMaterials>();

                    r.RawMaterialList = ListIngridients;
                    r.Save();

                    LoadRecipeList();
                }
                else
                {
                    MessageBox.Show(MessageIngridientMissing, TitleRecipe, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
        }

        private void lnkFirstBatchToPLC_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            if (lstActiveOrderList.SelectedItems.Count > 0)
            {
                int OrderId = 0;
                ListViewDataItem lst = lstActiveOrderList.SelectedItems[0];
                OrderId = (int)lst.Tag;
                Order o = new Order();
                o.FirstBatchToPLC(OrderId);

            }
        }

        private void commandBarButton1_Click(object sender, EventArgs e)
        {
            if (pvMainContent.SelectedPage != pvpOrder)
            {
                pvMainContent.Pages.Clear();
                pvMainContent.Pages.Add(pvpOrder);
            }
        }

        private void RecursiveControl(Control ctrl)
        {
            foreach (Control c in ctrl.Controls)
            {
                if (c is LinkLabel)
                {
                    LinkLabel lbl = (LinkLabel)c;
                    lbl.Text = "UI";
                    Debug.WriteLine(c.Name + " " + lbl.Text);
                }
                RecursiveControl(c); 
            }
        }

        private void btnBrowseRecipes_Click(object sender, EventArgs e)
        {
            frmPickList frm = new frmPickList(this._RawMaterialId, frmPickList.SelectType.TypeSingleSelect, frmPickList.ObjectType.TypeRecipe);
            frm.OnItemSelected += new frmPickList.Item_Selected(Recipe_Selected);
            frm.ShowDialog();
        }

        private void btnBrowseLocations_Click(object sender, EventArgs e)
        {
            frmPickList frm = new frmPickList(this._RawMaterialId, frmPickList.SelectType.TypeMultipleSelect, frmPickList.ObjectType.TypeLocation);
            frm.OnItemSelected += new frmPickList.Item_Selected(Location_Selected);
            frm.ShowDialog();
        }

        private void btnBrowseRawMaterials_Click(object sender, EventArgs e)
        {
            frmPickList frm = new frmPickList(this._RawMaterialId, frmPickList.SelectType.TypeMultipleSelect, frmPickList.ObjectType.TypeRawMaterial);
            frm.OnItemSelected += new frmPickList.Item_Selected(RawMaterialForRecipe_Selected);
            frm.ShowDialog();
        }

        private void lstRecipeList_DoubleClick(object sender, EventArgs e)
        {
            if (lstRecipeList.SelectedItem != null)
            {
                Int32 RecipeId = Convert.ToInt32(lstRecipeList.SelectedItem.Tag);
                LoadRecipe(RecipeId);
            }
        }

        private void btnMakeOrderFromRecipeList_Click(object sender, EventArgs e)
        {
            if (lstRecipeList.SelectedItem != null)
            {
                this._RecipeId = Convert.ToInt32(lstRecipeList.SelectedItem.Tag);

                btnMakeOrder_Click(null, null);
            }

        }

        private void btnAddNegativeRawMaterial_Click(object sender, EventArgs e)
        {
            frmPickList frm = new frmPickList(this._RawMaterialId, frmPickList.SelectType.TypeMultipleSelect, frmPickList.ObjectType.TypeRawMaterial);
            frm.OnItemSelected += new frmPickList.Item_Selected(RawMaterialNegative_Selected);
            frm.ShowDialog();
        }

        private void btnRemoveNegativeRawMatrerial_Click_1(object sender, EventArgs e)
        {
            if (lstRecipeNegativeList.SelectedItems.Count > 0)
            {
                if (MessageBox.Show(MessageIngridientRemove, TitleIngridient, MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.OK)
                {

                    RawMaterials r;
                    r = (RawMaterials)lstRecipeNegativeList.SelectedItems[0].Tag;

                    switch (r.RecordStatus)
                    {
                        case RawMaterials.eRecordStatus.IsAdded:
                            //Remove raw material from cache list since it is not saved to database
                            ListNegativeRawMaterials.Remove(r);
                            break;

                        case RawMaterials.eRecordStatus.IsNotChanged:
                            //Mark record for deletion on 'Save'
                            r.RecordStatus = RawMaterials.eRecordStatus.IsDeleted;
                            break;
                    }
                    lstRecipeNegativeList.Items.Remove(lstRecipeNegativeList.SelectedItems[0]);
                }
            }
        }

        private void btnAddStorageLocation_Click(object sender, EventArgs e)
        {
            frmPickList frm = new frmPickList(this._OrderId, frmPickList.SelectType.TypeMultipleSelect, frmPickList.ObjectType.TypeStorageLocation);
            frm.OnItemSelected += new frmPickList.Item_Selected(StorageLocation_Selected);
            frm.ShowDialog();
        }

        private void btnRemoveStorageLocation_Click(object sender, EventArgs e)
        {
            if (lstOrderStorage.SelectedItems.Count > 0)
            {
                lstOrderStorage.Items.Remove(lstOrderStorage.SelectedItems[0]);

                if (lstOrderStorage.Items.Count < 4) //Show max 4 entries
                {
                    lstOrderStorage.Height = lstOrderStorage.Items.Count * 20;
                }
                if (lstOrderStorage.Items.Count == 0)
                {
                    lstOrderStorage.Height = 20;
                }
            }
            if (lstOrderStorage.SelectedItems.Count == 0)
            {
                btnRemoveStorageLocation.Enabled = false;
            }
        }

        private void btnAddRecipe_Click(object sender, EventArgs e)
        {
            RecipeAddNew();
        }

        private void lstRecipeIngredients_ItemEditing(object sender, ListViewItemEditingEventArgs e)
        {
            RadListViewElement elm = (RadListViewElement)sender;


            if (elm.CurrentColumn.Name != "Column 3" && elm.CurrentColumn.Name != "Column 5")
            {
                e.Cancel = true;
            }
        }

        private void lstRecipeNegativeList_ItemEditing(object sender, ListViewItemEditingEventArgs e)
        {
            RadListViewElement elm = (RadListViewElement)sender;

            if (elm.CurrentColumn.Name != "Column 2") // Column 2 = Batch Flush
            {
                e.Cancel = true;
            }
        }

        private void lstRecipeNegativeList_ItemValidating(object sender, ListViewItemValidatingEventArgs e)
        {

            if (e.NewValue != e.OldValue)
            {

                RadListViewElement elm = (RadListViewElement)sender;
                RawMaterials r = (RawMaterials)elm.SelectedItem.Tag;

                if (validator == null) { validator = new InputValidator(); }
                validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
                validator.InputboxFrindlyName = "Batch Flush";
                validator.InputValue = e.NewValue.ToString();
                validator.MinValue = 1;
                validator.MaxValue = 1000;

                if (!validator.Validate())
                {
                    e.Cancel = true;
                    MessageBox.Show(validator.ValidationMessage, TitleOrderValidation, MessageBoxButtons.OK, validator.MessageBoxIcon);
                }
                else
                {
                    //Update cache list value for "Batch Flush"
                    foreach (RawMaterials rw in ListNegativeRawMaterials)
                    {
                        if (rw.RecipeId == r.RecipeId && rw.Id == r.Id)
                        {
                            rw.BatchFlush = Convert.ToInt16(e.NewValue);

                            if (rw.RecordStatus == RawMaterials.eRecordStatus.IsNotChanged)
                            {
                                rw.RecordStatus = RawMaterials.eRecordStatus.IsEdited;
                            }
                        }
                    }


                }

            }
        }

        private void btnDeleteRecipe_Click(object sender, EventArgs e)
        {

            if (lstRecipeList.SelectedItems.Count > 0)
            {
                if (MessageBox.Show(MessageRecipeDelete, TitleRecipe, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                {
                    int id = (int)lstRecipeList.SelectedItems[0].Tag;

                    Recipe r = new Recipe();
                    r.Id = id;
                    r.ActionType = Recipe.eActionType.TypeDeleteRecipe;
                    r.Save();

                    LoadRecipeList();
                }

            }
        }

        #region Input Validation

        private void lstRecipeIngredients_ItemValidating(object sender, ListViewItemValidatingEventArgs e)
        {

            if (e.NewValue != e.OldValue)
            {
                
                RadListViewElement elm = (RadListViewElement)sender;
                ListViewDetailColumn cl = elm.CurrentColumn;
                RawMaterials r = (RawMaterials)elm.SelectedItem.Tag;

                if (validator == null) { validator = new InputValidator(); }
                validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
                validator.InputboxFrindlyName = "Recipe";
                validator.InputValue = e.NewValue.ToString();
                validator.MinValue = 0.5m;
                validator.MaxValue = 100.1m;
                validator.DecimalAllowed = true;

                if (!validator.Validate())
                {
                    e.Cancel = true;
                    MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
                }
                else
                {

                    //Update cache list value for "Amount Procent" or "Tolerance %" for later saving
                    foreach (RawMaterials rw in ListIngridients)
                    {
                        if (rw.RecipeId == r.RecipeId && rw.Id == r.Id)
                        {
                            switch (cl.Name)
                            {
                                case "Column 5":  //Tolerance %
                                    rw.Tolerance = Convert.ToDecimal(e.NewValue);
                                    break;

                                case "Column 3": //Amount procent
                                    rw.AmountProcent = Convert.ToDecimal(e.NewValue);
                                    break;
                            }

                            if (rw.RecordStatus == RawMaterials.eRecordStatus.IsNotChanged)
                            {
                                rw.RecordStatus = RawMaterials.eRecordStatus.IsEdited;
                            }
                        }
                    }
                }

            }
        }

        private void txtOrderQuantum_Validating(object sender, CancelEventArgs e)
        {

                if (validator == null) { validator = new InputValidator(); }
                validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
                validator.InputboxFrindlyName = lblOrderQuantum.Text;
                validator.InputValue = txtOrderQuantum.Text;
                validator.MinValue = 1000;
                validator.MaxValue = 12000;
                //validator.LargeNumberAlert = 10000;
                validator.DecimalAllowed = false;
                validator.Validate();


                if (!validator.Valid)
                {
                    e.Cancel = true;
                    MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
                }
                else if (validator.Valid && validator.ValidButHeigh)
                {
                    MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
                } 
        }

        private void txtEndProductName_Validating(object sender, CancelEventArgs e)
        {

            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeText;
            validator.InputboxFrindlyName = lblEndProductName.Text;
            validator.InputValue = txtEndProductName.Text;
            validator.MinLength = 3;
            validator.MaxLength = 55;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }

        }

        private void txtRecBatchSize_Validating(object sender, CancelEventArgs e)
        {

            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
            validator.InputboxFrindlyName = lblRecBatchSize.Text;
            validator.InputValue = txtRecBatchSize.Text;
            validator.MinValue = 100;
            validator.MaxValue = 10000;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtRecipeName_Validating(object sender, CancelEventArgs e)
        {

            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeText;
            validator.InputboxFrindlyName = lblRecipeName.Text;
            validator.InputValue = txtRecipeName.Text;
            validator.MinLength = 3;
            validator.MaxLength = 55;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtRecipeNumber_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeText;
            validator.InputboxFrindlyName = lblRecipeNumber.Text;
            validator.InputValue = txtRecipeNumber.Text;
            validator.MinLength = 3;
            validator.MaxLength = 40;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void txtDefaultQuantum_Validating(object sender, CancelEventArgs e)
        {

            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
            validator.InputboxFrindlyName = lblRecipeDefaultQuantity.Text;
            validator.InputValue = txtDefaultQuantum.Text;
            validator.MinValue = 100;
            validator.MaxValue = 0;
            validator.LargeNumberAlert = 10000;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtRecipeRecBatchSize_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
            validator.InputboxFrindlyName = lblRecipeRecBatchSize.Text;
            validator.InputValue = txtRecipeRecBatchSize.Text;
            validator.MinValue = 100;
            validator.MaxValue = 4000;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtRecipeMinBatch_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
            validator.InputboxFrindlyName = lblRecipeMinimumBatchSize.Text;
            validator.InputValue = txtRecipeMinBatch.Text;
            validator.MinValue = 100;
            validator.MaxValue = 4000;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtRecipeEndProductName_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeText;
            validator.InputboxFrindlyName = lblEndProductName.Text;
            validator.InputValue = txtRecipeEndProductName.Text;
            validator.MinLength = 3;
            validator.MaxLength = 55;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }

        }

        private void txtRecBatchSize_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = ValidateNumeric(e.KeyValue);
        }

        private void txtOrderQuantum_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = ValidateNumeric(e.KeyValue);
        }

        private void txtDefaultQuantum_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = ValidateNumeric(e.KeyValue);
        }

        private void txtRecipeRecBatchSize_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = ValidateNumeric(e.KeyValue);
        }

        private void txtRecipeMinBatch_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = ValidateNumeric(e.KeyValue);
        }

        private void txtMaxVolume_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = ValidateNumeric(e.KeyValue); ;
        }

        private void txtMinVolume_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = ValidateNumeric(e.KeyValue);
        }

        private void txtVolume_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = ValidateNumeric(e.KeyValue);
        }

        private void txtTagListeGroupId_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = ValidateNumeric(e.KeyValue);
        }

        private void txtLocationPosition_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = ValidateNumeric(e.KeyValue);
        }

        private void txtRawMaterialDensity_KeyDown(object sender, KeyEventArgs e)
        {
           // e.SuppressKeyPress = ValidateNumeric(e.KeyValue);
        }

        private void txtLocationName_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeText;
            validator.InputboxFrindlyName = lblLocationName.Text;
            validator.InputValue = txtLocationName.Text;
            validator.MinLength = 3;
            validator.MaxLength = 55;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtMaxVolume_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
            validator.InputboxFrindlyName = lblLocationMaxVolume.Text;
            validator.InputValue = txtMaxVolume.Text;
            validator.MinValue = 10;
            validator.MaxValue = 10000;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtMinVolume_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
            validator.InputboxFrindlyName = lblLocationMinVolume.Text;
            validator.InputValue = txtMinVolume.Text;
            validator.MinValue = 10;
            validator.MaxValue = 4000;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtRawMaterialName_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeText;
            validator.InputboxFrindlyName = lblRawMaterialName.Text;
            validator.InputValue = txtRawMaterialName.Text;
            validator.MinLength = 3;
            validator.MaxLength = 55;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtRawMaterialNumber_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeText;
            validator.InputboxFrindlyName = lblRawMaterialNumber.Text;
            validator.InputValue = txtRawMaterialNumber.Text;
            validator.MinLength = 3;
            validator.MaxLength = 55;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtRawMaterialDensity_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
            validator.InputboxFrindlyName = lblRawMaterialDensity.Text;
            validator.InputValue = txtRawMaterialDensity.Text;
            validator.MinValue = 0;
            validator.MaxValue = 100;
            validator.DecimalAllowed = true;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        private void txtVolume_Validating(object sender, CancelEventArgs e)
        {
            if (validator == null) { validator = new InputValidator(); }
            validator.eInputValidationType = InputValidator.InputValidationType.TypeNumeric;
            validator.InputboxFrindlyName = lblLocationVolume.Text;
            validator.InputValue = txtVolume.Text;
            validator.MinValue = 100;
            validator.MaxValue = 20000;

            if (!validator.Validate())
            {
                e.Cancel = true;
                MessageBox.Show(validator.ValidationMessage, "Input Validation Message", MessageBoxButtons.OK, validator.MessageBoxIcon);
            }
        }

        #endregion

        /// <summary>
        /// Set Order in editmode
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditOrder_Click(object sender, EventArgs e)
        {
            Order o = new Order();
            o.Id = _OrderId;
            lstStatus.Items.Clear();


            switch (btnEditOrder.Tag.ToString())
            {
                case "1":
                    btnEditOrder.Tag = "2";

                    //Lock Order for Zenon/Production
                    o.SetOrderState(Order.OrderState.NotReady); //Sets flag so it is not requested by Zenon system 

                    txtOrderNumber.ReadOnly = false;
                    txtOrderQuantum.ReadOnly = false;
                    txtRecipe.ReadOnly = false;
                    btnBrowseRecipes.Enabled = true;
                    txtEndProductName.ReadOnly = false;
                    txtRecBatchSize.ReadOnly = false;
                    txtOrderMinBatchSize.ReadOnly = false;
                    btnAddStorageLocation.Enabled = true;
                    btnRemoveStorageLocation.Enabled = true;
                    btnValidateOrder.Enabled = true;
                    btnSendToProduction.Enabled = false;

                    btnEditOrder.Image = SetIcon("unlock");
                    btnEditOrder.Text = " Release Lock";

                    ValidationSetStatusMessages(OrderStatusScope.TypeOrderLocked, OrderStatusType.TypeLock, txtOrderNumber.Text);

                    break;

                case "2":
                    btnEditOrder.Tag = "1";

                    //Mark Order ready for Zenon/Production
                    o.SetOrderState(Order.OrderState.ReadyForProduction);

                    txtOrderNumber.ReadOnly = true;
                    txtOrderQuantum.ReadOnly = true;
                    txtRecipe.ReadOnly = true;
                    btnBrowseRecipes.Enabled = false;
                    txtEndProductName.ReadOnly = true;
                    txtRecBatchSize.ReadOnly = true;
                    txtOrderMinBatchSize.ReadOnly = true;
                    btnAddStorageLocation.Enabled = false;
                    btnRemoveStorageLocation.Enabled = false;
                    btnValidateOrder.Enabled = false;
                    btnSendToProduction.Enabled = false;

                    btnEditOrder.Image = SetIcon("lock");
                    btnEditOrder.Text = " Edit Mode";

                    ValidationSetStatusMessages(OrderStatusScope.TypeOrderReady, OrderStatusType.TypeOK, txtOrderNumber.Text);
                    break;


            }

   

        }

        #endregion

        private void btnSetPriority_Click(object sender, EventArgs e)
        {
            Order o = new Order();
            o.SetOrderStateAll(Order.OrderState.NotReady);
            OrderOrderList();

  

            frmSetOrderPriority frm = new frmSetOrderPriority();
            frm.ShowDialog();

            
        }

    }    
}

